// Package web counts visitors. Each App has its own count, so two Apps never // share anything. package web import ( "fmt" "log/slog" "net/http" "sync" ) // App holds what the handlers need. Make one with New. type App struct { mu sync.Mutex // protects visits visits int logger *slog.Logger greeting string } // New returns an App that logs to logger, and starts every reply with // greeting. func New(logger *slog.Logger, greeting string) *App { return &App{logger: logger, greeting: greeting} } // Handler returns the routes. func (a *App) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", a.handleHome) return mux } func (a *App) handleHome(w http.ResponseWriter, r *http.Request) { n := a.nextVisit() a.logger.Info("visit", "number", n) fmt.Fprintf(w, "%s You are visitor number %d.\n", a.greeting, n) } // nextVisit adds one to the count and returns it. func (a *App) nextVisit() int { a.mu.Lock() defer a.mu.Unlock() a.visits++ return a.visits }