forked from lyft/gostats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stat_handler.go
83 lines (66 loc) · 1.46 KB
/
stat_handler.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package stats
import (
"net/http"
"strconv"
"sync"
)
const requestTimer = "rq_time_us"
type httpHandler struct {
scope Scope
delegate http.Handler
timer Timer
codes map[int]Counter
codesMtx sync.RWMutex
}
// NewStatHandler returns an http handler for stats.
func NewStatHandler(scope Scope, handler http.Handler) http.Handler {
return &httpHandler{
scope: scope,
delegate: handler,
timer: scope.NewTimer(requestTimer),
codes: map[int]Counter{},
}
}
func (h *httpHandler) counter(code int) Counter {
h.codesMtx.RLock()
c := h.codes[code]
h.codesMtx.RUnlock()
if c != nil {
return c
}
h.codesMtx.Lock()
if c = h.codes[code]; c == nil {
c = h.scope.NewCounter(strconv.Itoa(code))
h.codes[code] = c
}
h.codesMtx.Unlock()
return c
}
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
span := h.timer.AllocateSpan()
h.delegate.ServeHTTP(h.wrapResponse(w), r)
span.Complete()
}
type responseWriter struct {
http.ResponseWriter
headerWritten bool
handler *httpHandler
}
func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.headerWritten {
rw.WriteHeader(http.StatusOK)
}
return rw.ResponseWriter.Write(b)
}
func (rw *responseWriter) WriteHeader(code int) {
if rw.headerWritten {
return
}
rw.headerWritten = true
rw.handler.counter(code).Inc()
rw.ResponseWriter.WriteHeader(code)
}
var (
_ http.Handler = (*httpHandler)(nil)
_ http.ResponseWriter = (*responseWriter)(nil)
)