-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
56 lines (48 loc) · 1.2 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 ski
import (
"context"
"sync"
)
// Context multiple values context
type Context interface {
context.Context
// SetValue store key with value
SetValue(key, value any)
}
type valuesCtx struct {
context.Context
values *sync.Map
}
func (c *valuesCtx) Value(key any) any {
value, ok := c.values.Load(key)
if ok {
return value
}
return c.Context.Value(key)
}
func (c *valuesCtx) SetValue(key, value any) { c.values.Store(key, value) }
var _ctxKey byte
// NewContext returns a new can store multiple values context with values
func NewContext(parent context.Context, values map[any]any) Context {
if parent == nil {
panic("cannot create context from nil parent")
}
m := new(sync.Map)
if values != nil {
for k, v := range values {
m.Store(k, v)
}
}
ctx := &valuesCtx{Context: parent, values: m}
m.Store(&_ctxKey, ctx)
return ctx
}
// WithValue if parent exists multiple values Context then set the key/value.
// or returns a copy of parent in which the value associated with key is val.
func WithValue(ctx context.Context, key, value any) context.Context {
if v, ok := ctx.Value(&_ctxKey).(*valuesCtx); ok {
v.SetValue(key, value)
return ctx
}
return context.WithValue(ctx, key, value)
}