/
prometheus.go
56 lines (45 loc) · 1.43 KB
/
prometheus.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
package prometheus
import (
"net/http"
"strconv"
"strings"
"github.com/felixge/httpsnoop"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type middleware struct {
buckets []float64
httpTotalRequests *prometheus.CounterVec
httpDuration *prometheus.HistogramVec
}
func New(opts ...Option) func(http.Handler) http.Handler {
m := &middleware{
buckets: []float64{0.5, 1, 2, 3, 5},
}
for _, opt := range opts {
opt(m)
}
m.httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_duration_seconds",
Help: "Duration of HTTP requests.",
Buckets: m.buckets,
}, []string{"path", "code", "method"})
m.httpTotalRequests = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Count of HTTP requests",
}, []string{"path", "code", "method"})
return m.handler
}
func (m *middleware) handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
metrics := httpsnoop.CaptureMetrics(next, w, r)
labels := []string{strings.ToLower(path), strconv.Itoa(metrics.Code), strings.ToLower(r.Method)}
go func() {
m.httpTotalRequests.WithLabelValues(labels...).Inc()
m.httpDuration.WithLabelValues(labels...).Observe(metrics.Duration.Seconds())
}()
})
}