-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
47 lines (39 loc) · 1.22 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
package refresh
import (
"net/http"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
)
type loggingMiddleware struct {
logger log.Logger
}
func NewLoggingMiddleware(logger log.Logger) *loggingMiddleware {
return &loggingMiddleware{logger}
}
func (l *loggingMiddleware) LoggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func(begin time.Time) {
l.logger.Log(
"took", time.Since(begin).Seconds(),
)
}(time.Now())
next.ServeHTTP(w, r)
})
}
type instrumentingMiddleware struct {
requestCount metrics.Counter
requestLatency metrics.Histogram
}
func NewInstrumentingMiddleware(counter metrics.Counter, histogram metrics.Histogram) *instrumentingMiddleware {
return &instrumentingMiddleware{counter, histogram}
}
func (i *instrumentingMiddleware) InstrumentingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func(begin time.Time) {
i.requestCount.With("path", r.URL.Path, "method", r.Method).Add(1)
i.requestLatency.With("path", r.URL.Path, "method", r.Method).Observe(time.Since(begin).Seconds())
}(time.Now())
next.ServeHTTP(w, r)
})
}