forked from thoas/stats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.go
46 lines (35 loc) · 992 Bytes
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/thoas/stats"
)
func StatsMiddleware(middleware *stats.Stats) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
beginning, recorder := middleware.Begin(w)
next.ServeHTTP(w, r)
middleware.End(beginning, stats.WithRecorder(recorder))
}
return http.HandlerFunc(fn)
}
}
func main() {
mux := chi.NewRouter()
Stats := stats.New()
mux.Use(StatsMiddleware(Stats))
mux.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"hello\": \"world\"}"))
})
mux.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
stats := Stats.Data()
b, _ := json.Marshal(stats)
w.Write(b)
})
fmt.Println("Serving on :8080")
http.ListenAndServe(":8080", mux)
}