-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
49 lines (41 loc) · 923 Bytes
/
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
package scene
import (
"sync"
)
// Context should be a "context container" that store module's context
type Context interface {
Get(key string) (value any, exists bool)
Set(key string, value any)
}
type defaultCtx struct {
values map[string]any
mux sync.RWMutex
}
func NewContext() Context {
return &defaultCtx{}
}
func (c *defaultCtx) Set(key string, value any) {
c.mux.Lock()
defer c.mux.Unlock()
if c.values == nil {
c.values = make(map[string]any)
}
c.values[key] = value
}
func (c *defaultCtx) Get(key string) (value any, exists bool) {
c.mux.RLock()
defer c.mux.RUnlock()
value, exists = c.values[key]
return value, exists
}
func ContextSetValue[T any](ctx Context, value T) {
ctx.Set(GetInterfaceName[T](), value)
}
func ContextFindValue[T any](ctx Context) (T, bool) {
v, ok := ctx.Get(GetInterfaceName[T]())
if !ok {
return *new(T), ok
}
valueT, ok := v.(T)
return valueT, ok
}