/
context.go
63 lines (50 loc) · 1.08 KB
/
context.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
package web
import (
"context"
"time"
)
type ctxKey int
const key ctxKey = 1
// Values represent state for each request.
type Values struct {
TraceID string
Now time.Time
StatusCode int
}
// GetValues returns the values from the context.
func GetValues(ctx context.Context) *Values {
v, ok := ctx.Value(key).(*Values)
if !ok {
return &Values{
TraceID: "00000000-0000-0000-0000-000000000000",
Now: time.Now(),
}
}
return v
}
// GetTraceID returns the trace id from the context.
func GetTraceID(ctx context.Context) string {
v, ok := ctx.Value(key).(*Values)
if !ok {
return "00000000-0000-0000-0000-000000000000"
}
return v.TraceID
}
// GetTime returns the time from the context.
func GetTime(ctx context.Context) time.Time {
v, ok := ctx.Value(key).(*Values)
if !ok {
return time.Now()
}
return v.Now
}
func setStatusCode(ctx context.Context, statusCode int) {
v, ok := ctx.Value(key).(*Values)
if !ok {
return
}
v.StatusCode = statusCode
}
func setValues(ctx context.Context, v *Values) context.Context {
return context.WithValue(ctx, key, v)
}