-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstatsd.go
61 lines (50 loc) · 1.34 KB
/
statsd.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package statsd
import "github.com/statsd/client-interface"
import "net/http"
import "time"
// wrapper to capture status.
type wrapper struct {
http.ResponseWriter
written int
status int
}
// capture status.
func (w *wrapper) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
// capture written bytes.
func (w *wrapper) Write(b []byte) (int, error) {
n, err := w.ResponseWriter.Write(b)
w.written += n
return n, err
}
// New statsd middleware with the given statsd client.
func New(stats statsd.Client) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
res := &wrapper{w, 0, 200}
// request count
stats.Incr("requests")
stats.Incr("requests.method." + req.Method)
// request size
stats.Histogram("request.size", int(req.ContentLength))
// serve
h.ServeHTTP(res, req)
// status
switch {
case res.status >= 200 && res.status < 300:
stats.Incr("response.ok")
case res.status >= 400 && res.status < 500:
stats.Incr("response.errors.client")
case res.status >= 500:
stats.Incr("response.errors.server")
}
// duration
stats.Duration("response.duration", time.Since(start))
// size
stats.Histogram("response.size", res.written)
})
}
}