-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
64 lines (55 loc) · 1.18 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
package context
type context struct {
Name string
Data map[string]interface{}
}
// Add singleton contexts identified by name
var (
ctxs map[string]*context
)
// Add context option 'WithData'
type ContextOption func(*context)
func WithData(data map[string]interface{}) ContextOption {
return func(ctx *context) {
ctx.Data = data
}
}
// Context returns the singleton context
func Context(name string, opts ...ContextOption) *context {
if ctxs == nil {
ctxs = make(map[string]*context)
}
if ctx, ok := ctxs[name]; ok {
return ctx
}
ctx := &context{
Name: name,
Data: make(map[string]interface{}),
}
// Loop through each option
for _, opt := range opts {
opt(ctx)
}
ctxs[name] = ctx
return ctx
}
func Exists(name string) bool {
if ctxs == nil {
return false
}
_, ok := ctxs[name]
return ok
}
// SetContext sets the singleton context
func (ctx *context) SetData(data map[string]interface{}) {
ctx.Data = data
}
// Get returns the value for a key
func (ctx *context) Get(key string) (interface{}, bool) {
value, ok := ctx.Data[key]
return value, ok
}
// Set sets the value for a key
func (ctx *context) Set(key string, value interface{}) {
ctx.Data[key] = value
}