-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathctx.go
65 lines (56 loc) · 2.01 KB
/
ctx.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
package apitestr
import (
"context"
"github.com/tomwright/apitestr/check"
)
type ctxKey string
const (
ctxBaseURLKey ctxKey = "baseUrl"
ctxCustomCheckKey ctxKey = "customBodyCheck_"
ctxRequestInitFunc ctxKey = "requestInitFunc_"
)
// ContextWithBaseURL stores the given base URL in the context
func ContextWithBaseURL(ctx context.Context, baseURL string) context.Context {
return context.WithValue(ctx, ctxBaseURLKey, baseURL)
}
// BaseURLFromContext returns the base URL to be used in tests, as stored in the given context
func BaseURLFromContext(ctx context.Context) string {
val := ctx.Value(ctxBaseURLKey)
if val == nil {
return ""
}
if str, ok := val.(string); ok {
return str
}
return ""
}
// ContextWithCustomBodyCheck stores a BodyCustomCheckerFunc into the context under the given id
func ContextWithCustomBodyCheck(ctx context.Context, checkID string, checkFunc check.BodyCustomCheckerFunc) context.Context {
return context.WithValue(ctx, ctxCustomCheckKey+ctxKey(checkID), checkFunc)
}
// CustomBodyCheckFromContext retrieves a BodyCustomCheckerFunc from the context by id
func CustomBodyCheckFromContext(ctx context.Context, checkID string) check.BodyCustomCheckerFunc {
val := ctx.Value(ctxCustomCheckKey + ctxKey(checkID))
if val == nil {
return nil
}
if checkFunc, ok := val.(check.BodyCustomCheckerFunc); ok {
return checkFunc
}
return nil
}
// ContextWithRequestInitFunc stores a RequestInitFunc into the context under the given id
func ContextWithRequestInitFunc(ctx context.Context, initFuncID string, requestInitFunc RequestInitFunc) context.Context {
return context.WithValue(ctx, ctxRequestInitFunc+ctxKey(initFuncID), requestInitFunc)
}
// RequestInitFuncFromContext retrieves a RequestInitFunc from the context by id
func RequestInitFuncFromContext(ctx context.Context, initFuncID string) RequestInitFunc {
val := ctx.Value(ctxRequestInitFunc + ctxKey(initFuncID))
if val == nil {
return nil
}
if requestInitFunc, ok := val.(RequestInitFunc); ok {
return requestInitFunc
}
return nil
}