-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
105 lines (86 loc) · 2.42 KB
/
context.go
File metadata and controls
105 lines (86 loc) · 2.42 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package traceable_context
import (
"context"
"github.com/google/uuid"
"time"
)
var uuidPrefix = `uuid`
// TraceableContext wrap the go context with a traceable uuid
type TraceableContext interface {
context.Context
// UUID returns the uuid inside the context
UUID() uuid.UUID
}
type traceableContext struct {
context.Context
uuid uuid.UUID
}
func WithCancel(parent context.Context) (ctx TraceableContext, cancel context.CancelFunc) {
c, cancel := context.WithCancel(parent)
return &traceableContext{
Context: c,
}, cancel
}
func WithDeadline(parent context.Context, deadline time.Time) (ctx TraceableContext, cancel context.CancelFunc) {
c, cancel := context.WithDeadline(parent, deadline)
return &traceableContext{
Context: c,
}, cancel
}
func WithTimeout(parent context.Context, timeout time.Duration) (ctx TraceableContext, cancel context.CancelFunc) {
c, cancel := context.WithTimeout(parent, timeout)
return &traceableContext{
Context: c,
}, cancel
}
func WithValue(parent context.Context, key, val interface{}) TraceableContext {
return &traceableContext{
Context: context.WithValue(parent, key, val),
}
}
// WithUUID creates a new traceable context from a given UUID
func WithUUID(uuid uuid.UUID) TraceableContext {
return &traceableContext{
Context: context.WithValue(context.Background(), &uuidPrefix, uuid),
uuid: uuid,
}
}
// FromContextWithUUID creates a new traceable context from a given parent context and a UUID
func FromContextWithUUID(parent context.Context, uuid uuid.UUID) TraceableContext {
return &traceableContext{
Context: context.WithValue(parent, &uuidPrefix, uuid),
uuid: uuid,
}
}
func Background() context.Context {
return &traceableContext{
Context: context.Background(),
}
}
// FromContext extracts the UUID from a given context
func FromContext(ctx context.Context) uuid.UUID {
uid, ok := ctx.Value(&uuidPrefix).(uuid.UUID)
if !ok {
return uuid.Nil
}
return uid
}
func (c *traceableContext) Deadline() (deadline time.Time, ok bool) {
return c.Context.Deadline()
}
func (c *traceableContext) Done() <-chan struct{} {
return c.Context.Done()
}
func (c *traceableContext) Err() error {
return c.Context.Err()
}
func (c *traceableContext) Value(key interface{}) interface{} {
return c.Context.Value(key)
}
func (c *traceableContext) UUID() uuid.UUID {
u, ok := c.Value(&uuidPrefix).(uuid.UUID)
if !ok {
panic(`traceableContext.uuid dose not exist`)
}
return u
}