-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
38 lines (30 loc) · 796 Bytes
/
http.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
package profiletimer
import (
"context"
"net/http"
)
type contextKey string
var (
contextKeyTimer = contextKey("timer")
)
func TimerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := StartProfileTimer()
r = requestWithTimer(r, timer)
next.ServeHTTP(w, r)
timer.ShowResults()
})
}
func TimerFromContext(ctx context.Context) Timer {
timer := ctx.Value(contextKeyTimer)
if timer == nil {
return StartNoopTimer()
}
return timer.(Timer)
}
func contextWithTimer(ctx context.Context, timer Timer) context.Context {
return context.WithValue(ctx, contextKeyTimer, timer)
}
func requestWithTimer(r *http.Request, timer Timer) *http.Request {
return r.WithContext(contextWithTimer(r.Context(), timer))
}