-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
middleware.go
68 lines (56 loc) · 1.72 KB
/
middleware.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
package prometheus
import (
"net/http"
"strings"
"time"
"github.com/julienschmidt/httprouter"
)
type MetricsManager struct {
prometheusMetrics *Metrics
routers []*httprouter.Router
}
func NewMetricsManager(app, version, hash, buildTime string) *MetricsManager {
return &MetricsManager{
prometheusMetrics: NewMetrics(app, version, hash, buildTime),
}
}
// Main middleware method to collect metrics for Prometheus.
func (pmm *MetricsManager) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
next(rw, r)
pmm.prometheusMetrics.ResponseTime.WithLabelValues(
pmm.getLabelForPath(r),
).Observe(time.Since(start).Seconds())
}
func (pmm *MetricsManager) RegisterRouter(router *httprouter.Router) {
pmm.routers = append(pmm.routers, router)
}
func (pmm *MetricsManager) getLabelForPath(r *http.Request) string {
// looking for a match in one of registered routers
for _, router := range pmm.routers {
handler, params, _ := router.Lookup(r.Method, r.URL.Path)
if handler != nil {
return reconstructEndpoint(r.URL.Path, params)
}
}
return "{unmatched}"
}
// To reduce cardinality of labels, values of matched path parameters must be replaced with {param}
func reconstructEndpoint(path string, params httprouter.Params) string {
// if map is empty, then nothing to change in the path
if len(params) == 0 {
return path
}
// construct a list of parameter values
paramValues := make(map[string]struct{}, len(params))
for _, param := range params {
paramValues[param.Value] = struct{}{}
}
parts := strings.Split(path, "/")
for index, part := range parts {
if _, ok := paramValues[part]; ok {
parts[index] = "{param}"
}
}
return strings.Join(parts, "/")
}