-
Notifications
You must be signed in to change notification settings - Fork 42
/
trace.go
56 lines (47 loc) · 1.06 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
package httplog
import (
"cmp"
"crypto/rand"
"encoding/hex"
"net/http"
)
const (
_headerTraceID = "X-Trace-ID"
_logFieldTrace = "trace_id"
_logFieldSpan = "span_id"
)
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "httplog context value " + k.name
}
var (
_contextKeyTrace = &contextKey{"trace_id"}
_contextKeySpan = &contextKey{"span_id"}
)
// NeTransport returns a new http.RoundTripper that propagates the TraceID.
func NewTransport(header string, base http.RoundTripper) http.RoundTripper {
if base == nil {
base = http.DefaultTransport
}
return traceTransport{
Header: cmp.Or(header, _headerTraceID),
Base: base,
}
}
type traceTransport struct {
Header string
Base http.RoundTripper
}
func (t traceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if id, ok := r.Context().Value(_contextKeyTrace).(string); ok {
r.Header.Set(cmp.Or(t.Header, _headerTraceID), id)
}
return t.Base.RoundTrip(r)
}
func newID() string {
b := make([]byte, 16)
rand.Read(b)
return hex.EncodeToString(b)
}