feat: Added chapter 2

This commit is contained in:
syrell 2024-10-14 23:00:46 +02:00
parent f7d9b3ffc7
commit c93e88b2fe
3 changed files with 38 additions and 2 deletions

13
main.go
View File

@ -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,

18
metrics.go Normal file
View File

@ -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)
}

9
reset.go Normal file
View File

@ -0,0 +1,9 @@
package main
import (
"net/http"
)
func (cfg *apiConfig) serveReset(w http.ResponseWriter, r *http.Request) {
cfg.fileserverHits.Store(0)
}