...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package baggage
16
17 import "context"
18
19 type baggageContextKeyType int
20
21 const baggageKey baggageContextKeyType = iota
22
23
24 type SetHookFunc func(context.Context, List) context.Context
25
26
27 type GetHookFunc func(context.Context, List) List
28
29 type baggageState struct {
30 list List
31
32 setHook SetHookFunc
33 getHook GetHookFunc
34 }
35
36
37
38
39
40 func ContextWithSetHook(parent context.Context, hook SetHookFunc) context.Context {
41 var s baggageState
42 if v, ok := parent.Value(baggageKey).(baggageState); ok {
43 s = v
44 }
45
46 s.setHook = hook
47 return context.WithValue(parent, baggageKey, s)
48 }
49
50
51
52
53
54 func ContextWithGetHook(parent context.Context, hook GetHookFunc) context.Context {
55 var s baggageState
56 if v, ok := parent.Value(baggageKey).(baggageState); ok {
57 s = v
58 }
59
60 s.getHook = hook
61 return context.WithValue(parent, baggageKey, s)
62 }
63
64
65
66 func ContextWithList(parent context.Context, list List) context.Context {
67 var s baggageState
68 if v, ok := parent.Value(baggageKey).(baggageState); ok {
69 s = v
70 }
71
72 s.list = list
73 ctx := context.WithValue(parent, baggageKey, s)
74 if s.setHook != nil {
75 ctx = s.setHook(ctx, list)
76 }
77
78 return ctx
79 }
80
81
82 func ListFromContext(ctx context.Context) List {
83 switch v := ctx.Value(baggageKey).(type) {
84 case baggageState:
85 if v.getHook != nil {
86 return v.getHook(ctx, v.list)
87 }
88 return v.list
89 default:
90 return nil
91 }
92 }
93
View as plain text