feat: Added chapter 2
This commit is contained in:
parent
f7d9b3ffc7
commit
c93e88b2fe
13
main.go
13
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,
|
||||
|
18
metrics.go
Normal file
18
metrics.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user