-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
46 lines (39 loc) · 979 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
package ctxslog
import (
"context"
"sync"
)
type ctxKey string
var fieldsKey ctxKey = "ctxslog_fields"
type safeMap struct {
mu sync.Mutex
fields map[string]any
}
func WithValue(ctx context.Context, k string, v any) context.Context {
if ctx == nil {
panic("cannot create context from nil parent")
}
if sm, ok := ctx.Value(fieldsKey).(*safeMap); ok {
sm.mu.Lock()
sm.fields[k] = v
sm.mu.Unlock()
return context.WithValue(ctx, fieldsKey, sm)
}
sm := &safeMap{fields: map[string]any{k: v}}
return context.WithValue(ctx, fieldsKey, sm)
}
func WithValues(ctx context.Context, fields map[string]any) context.Context {
if ctx == nil {
panic("cannot create context from nil parent")
}
if sm, ok := ctx.Value(fieldsKey).(*safeMap); ok {
sm.mu.Lock()
for k, v := range fields {
sm.fields[k] = v
}
sm.mu.Unlock()
return context.WithValue(ctx, fieldsKey, sm)
}
sm := &safeMap{fields: fields}
return context.WithValue(ctx, fieldsKey, sm)
}