...
1 package context
2
3 import (
4 "context"
5 "sync"
6
7 "github.com/docker/distribution/uuid"
8 )
9
10
11
12 type instanceContext struct {
13 context.Context
14 id string
15 once sync.Once
16 }
17
18 func (ic *instanceContext) Value(key interface{}) interface{} {
19 if key == "instance.id" {
20 ic.once.Do(func() {
21
22
23
24
25 ic.id = uuid.Generate().String()
26 })
27 return ic.id
28 }
29
30 return ic.Context.Value(key)
31 }
32
33 var background = &instanceContext{
34 Context: context.Background(),
35 }
36
37
38
39
40 func Background() context.Context {
41 return background
42 }
43
44
45
46 type stringMapContext struct {
47 context.Context
48 m map[string]interface{}
49 }
50
51
52
53 func WithValues(ctx context.Context, m map[string]interface{}) context.Context {
54 mo := make(map[string]interface{}, len(m))
55 for k, v := range m {
56 mo[k] = v
57 }
58
59 return stringMapContext{
60 Context: ctx,
61 m: mo,
62 }
63 }
64
65 func (smc stringMapContext) Value(key interface{}) interface{} {
66 if ks, ok := key.(string); ok {
67 if v, ok := smc.m[ks]; ok {
68 return v
69 }
70 }
71
72 return smc.Context.Value(key)
73 }
74
View as plain text