-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontext.go
More file actions
66 lines (57 loc) · 1.74 KB
/
context.go
File metadata and controls
66 lines (57 loc) · 1.74 KB
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
66
package dice
import (
"context"
)
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "dice context value " + k.name
}
var (
CtxKeyTotalRolls = &contextKey{name: "total rolls"}
CtxKeyMaxRolls = &contextKey{name: "max rolls"}
CtxKeyParameters = &contextKey{name: "parameters"}
)
// NewContextFromContext makes a child context from a given context, including
// setting the context's maximum rolls and adding a roll counter if not present.
func NewContextFromContext(ctx context.Context) context.Context {
// ensure a maximum roll value is present
if _, ok := ctx.Value(CtxKeyMaxRolls).(uint64); !ok {
ctx = context.WithValue(ctx, CtxKeyMaxRolls, MaxRolls)
}
// add a roll counter, if one doesn't exist
if _, ok := ctx.Value(CtxKeyTotalRolls).(*uint64); !ok {
return context.WithValue(ctx, CtxKeyTotalRolls, new(uint64))
}
return ctx
}
// CtxTotalRolls returns the pointer to total number of rolls made by the
// context.
func CtxTotalRolls(ctx context.Context) *uint64 {
if count, ok := ctx.Value(CtxKeyTotalRolls).(*uint64); ok {
return count
}
return new(uint64)
}
func MustCtxTotalRolls(ctx context.Context) *uint64 {
if count, ok := ctx.Value(CtxKeyTotalRolls).(*uint64); ok {
return count
}
panic(ErrContextKeyMissing)
}
// CtxMaxRolls returns the context's maximum allowed number of rolls, or the
// default.
func CtxMaxRolls(ctx context.Context) uint64 {
if max, ok := ctx.Value(CtxKeyMaxRolls).(uint64); ok {
return max
}
return MaxRolls
}
// CtxParameters returns the context's arbitrary parameters.
func CtxParameters(ctx context.Context) map[string]interface{} {
if params, ok := ctx.Value(CtxKeyParameters).(map[string]interface{}); ok {
return params
}
return make(map[string]interface{})
}