-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
95 lines (82 loc) · 2.45 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package thetis
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
//Handler is a custom implementation of an http.Handler
//that calls the custom metrics on every route.
type Handler struct {
metrics []Metric
handlers []http.Handler
wrappedHandler http.Handler
}
//Metric is a definition of a prometheus metric.
//It will return the prometheus.Collector to be used
//And Call the returned http.HandlerFunc
//for every request handled
type Metric interface {
GetCollector() prometheus.Collector
CreateHandler() http.HandlerFunc
}
//NewWithDefaults returns an http.Handler that process
//all the requests. Receives a router, which contains
//your logic.
func NewWithDefaults(router http.Handler) *Handler {
return &Handler{
metrics: []Metric{&httpMetric{}},
wrappedHandler: router,
}
}
//NewHandler returns an http.Handler without metrics.
//You need to add your custom metrics using Add()
func NewHandler(router http.Handler) *Handler {
metrics := make([]Metric, 0)
return &Handler{
metrics: metrics,
wrappedHandler: router,
}
}
//Add appends your custom metrics to the chain of
//callable handlers
func (h *Handler) Add(c ...Metric) {
h.metrics = append(h.metrics, c...)
}
//RegisterAll registers the given Collectors.
//calls to prometheus.MustRegister could panic, please check the documentation
func (h *Handler) RegisterAll() http.Handler {
collectors := make([]prometheus.Collector, len(h.metrics))
h.handlers = make([]http.Handler, len(collectors))
for i, m := range h.metrics {
collectors[i] = m.GetCollector()
h.handlers[i] = m.CreateHandler()
}
prometheus.MustRegister(collectors...)
return promhttp.Handler()
}
//ServeHTTP implements the http.Handler interface
//it must be used after a single call of RegisterAll
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{w: w}
h.wrappedHandler.ServeHTTP(sw, r)
for _, h := range h.handlers {
h.ServeHTTP(sw, r)
}
}
//statusWriter is a custom implementation of
//an http.ResponseWriter that can
//preserve the http status written in the response
type statusWriter struct {
status int
w http.ResponseWriter
}
func (s *statusWriter) WriteHeader(status int) {
s.status = status
s.w.WriteHeader(status)
}
func (s *statusWriter) Write(data []byte) (int, error) {
return s.w.Write(data)
}
func (s *statusWriter) Header() http.Header {
return s.w.Header()
}