-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
67 lines (52 loc) · 1.28 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
// Package `trace_ctx` enables precise control over the
// setting and retrieval of the `trace_id` within a context,
// ensuring that the unique identifier is consistently managed
// throughout the lifecycle of a request.
//
// This capability is essential for maintaining traceability
// and correlating log entries across different components
// of the application.
package trace_ctx
import (
"context"
)
var (
TraceKeyInCtx any = new(Trace)
)
const (
TraceIDKeyName = "trace_id"
)
func GetTraceID(ctx context.Context) TraceID {
if ctx == nil {
panic("ctx is nil")
}
return GetTrace(ctx).ID
}
func WithTraceID(ctx context.Context) context.Context {
if ctx == nil {
panic("ctx is nil")
}
return context.WithValue(ctx, TraceKeyInCtx, NewTrace())
}
func SetTraceID(ctx context.Context, traceID TraceID) context.Context {
if ctx == nil {
panic("ctx is nil")
}
return context.WithValue(ctx, TraceKeyInCtx, NewTraceWithID(traceID))
}
func WithTrace(ctx context.Context, trace *Trace) context.Context {
if ctx == nil {
panic("ctx is nil")
}
return context.WithValue(ctx, TraceKeyInCtx, trace)
}
func GetTrace(ctx context.Context) *Trace {
if ctx == nil {
panic("ctx is nil")
}
val := ctx.Value(TraceKeyInCtx)
if val != nil {
return val.(*Trace)
}
return NewTrace()
}