From c93e88b2fe0b465b87a0620951329f8ef92c7fbb Mon Sep 17 00:00:00 2001 From: syrell Date: Mon, 14 Oct 2024 23:00:46 +0200 Subject: [PATCH] feat: Added chapter 2 --- main.go | 13 +++++++++++-- metrics.go | 18 ++++++++++++++++++ reset.go | 9 +++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 metrics.go create mode 100644 reset.go diff --git a/main.go b/main.go index 1913d4b..10112ee 100644 --- a/main.go +++ b/main.go @@ -2,18 +2,27 @@ package main import ( "net/http" + "sync/atomic" ) +type apiConfig struct { + fileserverHits atomic.Int32 +} + func main() { + apiCfg := &apiConfig{} mux := http.NewServeMux() fileServer := http.FileServer(http.Dir(".")) - mux.Handle("/app", http.StripPrefix("/app", fileServer)) + mux.Handle("/app", apiCfg.middlewareMetricsInc(http.StripPrefix("/app", fileServer))) mux.Handle("/app/assets/", http.StripPrefix("/app/assets/", http.FileServer(http.Dir("./assets/")))) - mux.HandleFunc("/healthz", func(w http.ResponseWriter, req *http.Request) { + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, req *http.Request) { req.Header.Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }) + mux.Handle("GET /metrics", http.HandlerFunc(apiCfg.serveMetrics)) + mux.Handle("POST /reset", http.HandlerFunc(apiCfg.serveReset)) + server := &http.Server{ Addr: ":8080", Handler: mux, diff --git a/metrics.go b/metrics.go new file mode 100644 index 0000000..961d6d1 --- /dev/null +++ b/metrics.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "net/http" +) + +func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + cfg.fileserverHits.Add(1) + next.ServeHTTP(w, req) + }) +} + +func (cfg *apiConfig) serveMetrics(w http.ResponseWriter, r *http.Request) { + hits := cfg.fileserverHits.Load() + fmt.Fprintf(w, "Hits: %d", hits) +} diff --git a/reset.go b/reset.go new file mode 100644 index 0000000..4513334 --- /dev/null +++ b/reset.go @@ -0,0 +1,9 @@ +package main + +import ( + "net/http" +) + +func (cfg *apiConfig) serveReset(w http.ResponseWriter, r *http.Request) { + cfg.fileserverHits.Store(0) +}