-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.go
69 lines (59 loc) · 1.3 KB
/
basic.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
package context
import (
"context"
"github.com/google/uuid"
"go.opentelemetry.io/otel/trace"
)
type Context struct {
ctx context.Context
TraceID string
Values map[string]any
}
func NewContext(ctx context.Context) *Context {
var traceId string
if ctx != nil {
span := trace.SpanFromContext(ctx)
if spanContext := span.SpanContext(); spanContext.IsValid() {
traceId = spanContext.TraceID().String()
}
} else {
ctx = context.Background()
}
if traceId == "" {
traceId = uuid.New().String()
}
return &Context{
ctx: ctx,
TraceID: traceId,
Values: map[string]any{},
}
}
func (c *Context) StartSpan(name string, o ...trace.SpanStartOption) (*Context, trace.Span) {
ctx, span := tracer.Start(c.ctx, name, o...)
c.ctx = ctx
if c.TraceID == "" {
c.TraceID = span.SpanContext().TraceID().String()
}
return c, span
}
func (c *Context) ContextWrapper() context.Context {
return context.WithValue(c.ctx, ctxKey{}, c)
}
func ContextFromContext(ctx context.Context) *Context {
if ctx == nil {
return NewContext(context.Background())
}
ctxi := ctx.Value(ctxKey{})
c, ok := ctxi.(*Context)
if !ok {
c = NewContext(ctx)
}
c.ctx = ctx
return c
}
func (c *Context) Context() context.Context {
return c.ctx
}
func (c *Context) SetContext(ctx context.Context) {
c.ctx = ctx
}