Skip to content

Commit 78cf706

Browse files
committed
improved net/http example
1 parent 69e3c07 commit 78cf706

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

examples/nethttp/server.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
package main
22

33
import (
4-
"github.com/thoas/stats"
4+
"encoding/json"
55
"net/http"
6+
7+
"github.com/thoas/stats"
68
)
79

810
func main() {
9-
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11+
middleware := stats.New()
12+
mux := http.NewServeMux()
13+
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
1014
w.Header().Set("Content-Type", "application/json")
1115
w.Write([]byte("{\"hello\": \"world\"}"))
1216
})
13-
14-
handler := stats.New().Handler(h)
15-
http.ListenAndServe(":8080", handler)
17+
mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
18+
w.Header().Set("Content-Type", "application/json")
19+
b, _ := json.Marshal(middleware.Data())
20+
w.Write(b)
21+
})
22+
http.ListenAndServe(":8080", middleware.Handler(mux))
1623
}

0 commit comments

Comments
 (0)