-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathcontext.go
56 lines (46 loc) · 1.39 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
package validate
import (
"context"
)
// validateCtxKey is the key type of context key in this pkg
type validateCtxKey string
const (
operationTypeKey validateCtxKey = "operationTypeKey"
)
type operationType string
const (
request operationType = "request"
response operationType = "response"
none operationType = "none" // not specified in ctx
)
var operationTypeEnum = []operationType{request, response, none}
// WithOperationRequest returns a new context with operationType request
// in context value
func WithOperationRequest(ctx context.Context) context.Context {
return withOperation(ctx, request)
}
// WithOperationRequest returns a new context with operationType response
// in context value
func WithOperationResponse(ctx context.Context) context.Context {
return withOperation(ctx, response)
}
func withOperation(ctx context.Context, operation operationType) context.Context {
return context.WithValue(ctx, operationTypeKey, operation)
}
// extractOperationType extracts the operation type from ctx
// if not specified or of unknown value, return none operation type
func extractOperationType(ctx context.Context) operationType {
v := ctx.Value(operationTypeKey)
if v == nil {
return none
}
res, ok := v.(operationType)
if !ok {
return none
}
// validate the value is in operation enum
if err := Enum("", "", res, operationTypeEnum); err != nil {
return none
}
return res
}