-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracer.go
90 lines (78 loc) · 2.08 KB
/
tracer.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
package luchen
import (
"context"
"net/http"
"strings"
"github.com/google/uuid"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
const (
// TraceIDHeader traceID header key
TraceIDHeader = "X-Trace-ID"
)
type (
traceIDKey struct{}
)
var (
// TraceIDCtxKey traceID context key
TraceIDCtxKey = traceIDKey{}
)
// TraceHTTPRequest 返回 traceID
// http 请求携带 traceID 处理
func TraceHTTPRequest(r *http.Request) (*http.Request, string) {
traceID := r.Header.Get(TraceIDHeader)
if traceID == "" {
traceID = TraceID(r.Context())
}
if traceID == "" {
traceID = genTraceID()
}
r.Header.Set(TraceIDHeader, traceID)
ctx := WithTraceID(r.Context(), traceID)
return r.WithContext(ctx), traceID
}
// TraceGRPC 返回 traceID
// grpc 请求携带 traceID 处理
func TraceGRPC(ctx context.Context, md metadata.MD) (context.Context, string) {
traceID := genTraceID()
if len(md.Get(TraceIDHeader)) > 0 {
traceID = md.Get(TraceIDHeader)[0]
}
md.Set(TraceIDHeader, traceID)
ctx = WithTraceID(ctx, traceID)
return ctx, traceID
}
// TraceGRPCClient grpc client 携带 traceID
func TraceGRPCClient(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
traceID := TraceID(ctx)
if traceID == "" {
traceID = genTraceID()
ctx = WithTraceID(ctx, traceID)
}
ctx = metadata.AppendToOutgoingContext(ctx, TraceIDHeader, traceID)
return invoker(ctx, method, req, reply, cc, opts...)
}
// TraceID 从 context 获得 TraceID
func TraceID(ctx context.Context) string {
value := ctx.Value(TraceIDCtxKey)
if value == nil {
return ""
}
return value.(string)
}
// TraceIDOrNew 从 context 获得 TraceID,取不到则创建
func TraceIDOrNew(ctx context.Context) string {
traceID := TraceID(ctx)
if traceID == "" {
return genTraceID()
}
return traceID
}
// WithTraceID context 注入 traceID
func WithTraceID(ctx context.Context, traceID string) context.Context {
return context.WithValue(ctx, TraceIDCtxKey, traceID)
}
func genTraceID() string {
return strings.ReplaceAll(uuid.NewString(), "-", "")
}