-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-timing.go
54 lines (42 loc) · 1.1 KB
/
server-timing.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
package middleware
import (
"net/http"
"github.com/mitchellh/go-server-timing"
"go.sancus.dev/web"
"go.sancus.dev/web/middleware"
)
// Middleware to enable Server-Time if a given function agrees,
// or unconditionally if none given
func ServerTimer(allowed func(r *http.Request) bool) web.MiddlewareHandlerFunc {
timed := func(next http.Handler) http.Handler {
return servertiming.Middleware(next, nil)
}
if allowed == nil {
// unconditional
return timed
}
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if allowed(r) {
next = timed(next)
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
// Middleware to produce a Server-Timer metric
func ServerTimerMetric(name string) web.MiddlewareHandlerFunc {
if len(name) == 0 {
return middleware.NOP
}
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if t := servertiming.FromContext(r.Context()); t != nil {
defer t.NewMetric(name).Start().Stop()
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}