/
context.go
109 lines (90 loc) ยท 2.35 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
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
106
107
108
109
package share
import (
"context"
"errors"
"fmt"
"reflect"
opentracing "github.com/opentracing/opentracing-go"
"go.opencensus.io/trace"
)
// var _ context.Context = &Context{}
// Context is a rpcx customized Context that can contains multiple values.
type Context struct {
tags map[interface{}]interface{}
context.Context
}
func NewContext(ctx context.Context) *Context {
return &Context{
Context: ctx,
tags: make(map[interface{}]interface{}),
}
}
func (c *Context) Value(key interface{}) interface{} {
if c.tags == nil {
c.tags = make(map[interface{}]interface{})
}
if v, ok := c.tags[key]; ok {
return v
}
return c.Context.Value(key)
}
func (c *Context) SetValue(key, val interface{}) {
if c.tags == nil {
c.tags = make(map[interface{}]interface{})
}
c.tags[key] = val
}
func (c *Context) String() string {
return fmt.Sprintf("%v.WithValue(%v)", c.Context, c.tags)
}
func WithValue(parent context.Context, key, val interface{}) *Context {
if key == nil {
panic("nil key")
}
if !reflect.TypeOf(key).Comparable() {
panic("key is not comparable")
}
tags := make(map[interface{}]interface{})
tags[key] = val
return &Context{Context: parent, tags: tags}
}
func WithLocalValue(ctx *Context, key, val interface{}) *Context {
if key == nil {
panic("nil key")
}
if !reflect.TypeOf(key).Comparable() {
panic("key is not comparable")
}
if ctx.tags == nil {
ctx.tags = make(map[interface{}]interface{})
}
ctx.tags[key] = val
return ctx
}
// GetSpanContextFromContext get opentracing.SpanContext from context.Context.
func GetSpanContextFromContext(ctx context.Context) (opentracing.SpanContext, error) {
reqMeta, ok := ctx.Value(ReqMetaDataKey).(map[string]string)
if !ok {
return nil, nil
}
return opentracing.GlobalTracer().Extract(
opentracing.TextMap,
opentracing.TextMapCarrier(reqMeta))
}
// GetOpencensusSpanContextFromContext get opencensus.trace.SpanContext from context.Context.
func GetOpencensusSpanContextFromContext(ctx context.Context) (*trace.SpanContext, error) {
reqMeta, ok := ctx.Value(ReqMetaDataKey).(map[string]string)
if !ok {
return nil, nil
}
spanKey := reqMeta[OpencensusSpanRequestKey]
if spanKey == "" {
return nil, errors.New("key not found")
}
data := []byte(spanKey)
_ = data[23]
t := &trace.SpanContext{}
copy(t.TraceID[:], data[:16])
copy(t.SpanID[:], data[16:24])
return t, nil
}