forked from LyricTian/gin-admin
/
context.go
42 lines (36 loc) · 912 Bytes
/
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
package util
import (
"context"
)
type (
traceIDContextKey struct{}
userIDContextKey struct{}
)
// NewTraceIDContext 创建跟踪ID上下文
func NewTraceIDContext(ctx context.Context, traceID string) context.Context {
return context.WithValue(ctx, traceIDContextKey{}, traceID)
}
// FromTraceIDContext 从上下文中获取跟踪ID
func FromTraceIDContext(ctx context.Context) string {
v := ctx.Value(traceIDContextKey{})
if v != nil {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// NewUserIDContext 创建用户ID上下文
func NewUserIDContext(ctx context.Context, userID string) context.Context {
return context.WithValue(ctx, userIDContextKey{}, userID)
}
// FromUserIDContext 从上下文中获取用户ID
func FromUserIDContext(ctx context.Context) string {
v := ctx.Value(userIDContextKey{})
if v != nil {
if s, ok := v.(string); ok {
return s
}
}
return ""
}