-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathctx.go
More file actions
66 lines (55 loc) · 1.47 KB
/
Copy pathctx.go
File metadata and controls
66 lines (55 loc) · 1.47 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
package gtrace
import (
"context"
"github.com/opentracing/opentracing-go"
)
const (
// IdKey is the key string format of trace id.
IdKey = "tid"
// HeaderKey is the request id key in http header.
HeaderKey = "X-Request-Id"
// Used when no trace id found or generated failed.
//DefaultTraceIdValue = "none"
)
type ctxIdKey struct{}
// ContextWithId store the trace id in context.Value.
func ContextWithId(ctx context.Context, tid string) context.Context {
if tid == "" {
return ctx
}
// Do not store duplicate id.
if _id, ok := ctx.Value(ctxIdKey{}).(string); ok && _id == tid {
return ctx
}
return context.WithValue(ctx, ctxIdKey{}, tid)
}
// IdFromContext get the trace id from context.Value.
func IdFromContext(ctx context.Context) (id string) {
var ok bool
id, ok = ctx.Value(ctxIdKey{}).(string)
if !ok {
id = ""
}
return
}
type ctxTracerKey struct{}
// ContextWithTracer store the tracer instances to context.Value.
func ContextWithTracer(ctx context.Context, tracer Tracer) context.Context {
if tracer == nil {
return ctx
}
// Do not store duplicate id.
if _tracer, ok := ctx.Value(ctxTracerKey{}).(Tracer); ok && _tracer == tracer {
return ctx
}
return context.WithValue(ctx, ctxTracerKey{}, tracer)
}
// TracerFromContext get the tracer instances from context.Value.
func TracerFromContext(ctx context.Context) (tracer Tracer) {
var ok bool
tracer, ok = ctx.Value(ctxTracerKey{}).(Tracer)
if !ok {
tracer = opentracing.NoopTracer{}
}
return
}