-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
65 lines (53 loc) · 1.42 KB
/
time.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
//spellchecker:words wrap
package wrap
//spellchecker:words context http time
import (
"context"
"net/http"
"time"
)
//spellchecker:words timewrap
// requestTime is a type for storing the request time
type requestTime struct{}
var requestTimeKey = requestTime{}
// Time wraps an [http.Handler], storing the time a request was started within it.
// To retrieve stored time, see [TimeStart] and [TimeSince].
func Time(h http.Handler) http.Handler {
return Context(h, func(r *http.Request) (context.Context, context.CancelFunc) {
return context.WithValue(r.Context(), requestTimeKey, time.Now()), nil
})
}
// TimeStart returns the time that the request r was started.
// Must be called from within a handler wrapped with [Time].
// If no time is stored, returns the current time.
func TimeStart(r *http.Request) time.Time {
if r == nil {
return time.Now()
}
start := r.Context().Value(requestTimeKey)
if start == nil {
return time.Now()
}
t, ok := start.(time.Time)
if !ok {
return time.Now()
}
return t
}
// TimeSince returns the time since the request r was started.
// Must be called from within a handler wrapped with [Time] to be effective.
// If no time is stored in the request, returns 0.
func TimeSince(r *http.Request) time.Duration {
if r == nil {
return 0
}
start := r.Context().Value(requestTimeKey)
if start == nil {
return 0
}
t, ok := start.(time.Time)
if !ok {
return 0
}
return time.Since(t)
}