-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrace.go
70 lines (58 loc) · 1.64 KB
/
trace.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
package trace
import (
"encoding/hex"
"net/http"
"github.com/golang/glog"
"github.com/pborman/uuid"
"golang.org/x/net/context"
)
type traceIdKey struct{}
// Struct traceInfo defines the trace info.
type traceInfo struct {
Tid string // The trace ID.
}
func GenerateTraceId() string {
id := uuid.NewRandom()
var buf [32]byte
hex.Encode(buf[:], id[:])
tid := string(buf[:])
glog.V(2).Infof("Generated traceId:%s", tid)
return tid
}
// NewTraceId returns a copy of parent context in which
// a new trace ID is created and attached.
func NewTraceId(parent context.Context) context.Context {
ti := traceInfo{
Tid: GenerateTraceId(),
}
return context.WithValue(parent, traceIdKey{}, &ti)
}
// WithTraceId returns a copy of parent context in which
// the given trace ID is attached.
func WithTraceId(parent context.Context, tid string) context.Context {
ti := traceInfo{
Tid: tid,
}
return context.WithValue(parent, traceIdKey{}, &ti)
}
// GetTraceId returns the trace ID from the given context.
func GetTraceId(ctx context.Context) (tid string, ok bool) {
if ti, ok := ctx.Value(traceIdKey{}).(*traceInfo); ok {
return ti.Tid, ok
}
return "", false
}
// GetTraceIdOrEmpty returns the trace ID from the given context or
// an empty string if the trace ID is not found.
func GetTraceIdOrEmpty(ctx context.Context) string {
if ti, ok := ctx.Value(traceIdKey{}).(*traceInfo); ok {
return ti.Tid
}
return ""
}
// SetTraceIdHeader add trace id to HTTTP Header X-Request-Id.
func SetTraceIdHeader(ctx context.Context, w http.ResponseWriter) {
if ti, ok := ctx.Value(traceIdKey{}).(*traceInfo); ok {
w.Header().Set("X-Request-Id", ti.Tid)
}
}