-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcontext.go
68 lines (59 loc) · 1.28 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
57
58
59
60
61
62
63
64
65
66
67
68
package astilog
import (
"context"
"sync"
)
type contextKey string
const contextKeyFields contextKey = "astilog.fields"
type contextFields struct {
fs map[string]interface{}
m *sync.Mutex
}
func newContextFields() *contextFields {
return &contextFields{
fs: make(map[string]interface{}),
m: &sync.Mutex{},
}
}
func fieldsFromContext(ctx context.Context) *contextFields {
if ctx == nil {
return nil
}
v, ok := ctx.Value(contextKeyFields).(*contextFields)
if !ok {
return nil
}
return v
}
func FieldsFromContext(ctx context.Context) (fs map[string]interface{}) {
if cfs := fieldsFromContext(ctx); cfs != nil {
cfs.m.Lock()
fs = make(map[string]interface{})
for k, v := range cfs.fs {
fs[k] = v
}
cfs.m.Unlock()
return
}
return
}
func ContextWithField(ctx context.Context, k string, v interface{}) context.Context {
return ContextWithFields(ctx, map[string]interface{}{k: v})
}
func ContextWithFields(ctx context.Context, fs map[string]interface{}) context.Context {
if ctx == nil {
return nil
}
cfs := newContextFields()
if ccfs := fieldsFromContext(ctx); ccfs != nil {
ccfs.m.Lock()
for k, v := range ccfs.fs {
cfs.fs[k] = v
}
ccfs.m.Unlock()
}
for k, v := range fs {
cfs.fs[k] = v
}
return context.WithValue(ctx, contextKeyFields, cfs)
}