-
Notifications
You must be signed in to change notification settings - Fork 32
/
handler.go
77 lines (67 loc) · 1.83 KB
/
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
package stats
import (
"fmt"
"net/http"
"time"
"github.com/mholt/caddy/middleware"
"github.com/rcrowley/go-metrics"
)
func (m *metricsModule) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
next := m.next
path := ""
if m.uiPath != "" && middleware.Path(r.URL.Path).Matches(m.uiPath) {
next = statsHandler{}
path = "getStats"
}
if path == "" {
path = m.pathName(r.URL.Path, r.Method)
}
//every datapoint gets tagged with server and path. A few get some extra.
tags := func(extra ...string) map[string]string {
m := map[string]string{"path": path, "server": m.serverName}
if len(extra)%2 == 0 {
for i := 1; i < len(extra); i += 2 {
m[extra[i-1]] = extra[i]
}
}
return m
}
start := time.Now()
code, err := next.ServeHTTP(w, r)
duration := time.Now().Sub(start)
mname := MetricName("caddy.requests", tags("status", fmt.Sprint(code)))
counter := metrics.GetOrRegisterCounter(mname, metrics.DefaultRegistry)
counter.Inc(1)
mname = MetricName("caddy.errors", tags())
counter = metrics.GetOrRegisterCounter(mname, metrics.DefaultRegistry)
if err != nil {
counter.Inc(1)
}
mname = MetricName("caddy.response_time", tags())
timer := metrics.GetOrRegisterTimer(mname, metrics.DefaultRegistry)
timer.Update(duration)
return code, err
}
type statsHandler struct{}
func (s statsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
snapshotLock.RLock()
defer snapshotLock.RUnlock()
w.Write(currentJSON)
w.Header().Set("Content-Type", "application/json")
return 200, nil
}
func (m *metricsModule) pathName(url string, method string) string {
for _, pth := range m.paths {
if middleware.Path(url).Matches(pth.path) {
if pth.methods == nil {
return pth.name
}
for _, m := range pth.methods {
if m == method {
return pth.name
}
}
}
}
return "/"
}