-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecord.go
More file actions
41 lines (34 loc) · 845 Bytes
/
record.go
File metadata and controls
41 lines (34 loc) · 845 Bytes
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
package httpinfo
import (
"context"
"net/http"
"time"
)
type ctxKey string
const ctxKeyRR = ctxKey("rr")
// Record records the http response information and helps to reach
// them from any other middleware. See examples on how to use it.
func Record(opts ...Option) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
rr = &responseRecorder{
writer: rw,
routeGetter: func(r *http.Request) string {
return r.Method + " " + r.URL.Path
},
start: time.Now(),
}
)
defer rr.WriteHeaderNow()
for _, opt := range opts {
opt(rr)
}
ctx = context.WithValue(ctx, ctxKeyRR, rr)
rw = rr.wrapped()
r = r.WithContext(ctx)
next.ServeHTTP(rw, r)
})
}
}