forked from ori-shem-tov/algosearch
/
context.go
48 lines (41 loc) · 1.02 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
package web
import (
"context"
"errors"
"time"
)
// ctxKey represents the type of value for the context key.
type ctxKey int
// key is how request values are stored/retrieved.
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, error) {
v, ok := ctx.Value(key).(*Values)
if !ok {
return nil, errors.New("web value missing from context")
}
return v, nil
}
// 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
}
// SetStatusCode sets the status code back into the context.
func SetStatusCode(ctx context.Context, statusCode int) error {
v, ok := ctx.Value(key).(*Values)
if !ok {
return errors.New("web value missing from context")
}
v.StatusCode = statusCode
return nil
}