-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext.go
More file actions
74 lines (64 loc) · 2.22 KB
/
context.go
File metadata and controls
74 lines (64 loc) · 2.22 KB
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
package logging
import (
"context"
"net/http"
"github.com/smallstep/logging/tracing"
)
type key int
const (
// traceheaderKey is the context key that should store the request identifier.
traceheaderKey key = iota
// nameKey is the context key used to stored the log name.
nameKey
)
// Tracing returns a new middleware that gets the given header and sets it in
// the context so it can be written in the logger. If the header does not exists
// or it's the empty string, it uses github.com/smallstep/tracing to create a
// new one.
func Tracing(headerName string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
var err error
var tp *tracing.Traceparent
// Parse traceparent if available. Ignore errors.
if s := req.Header.Get(headerName); s != "" {
tp, _ = tracing.Parse(s)
}
// If no traceparent or bad, generate a new one.
// Do not fail if we can't generate the tracing id.
if tp == nil {
if tp, err = tracing.New(); err != nil {
return
}
req.Header.Set(headerName, tp.String())
}
ctx := WithTraceparent(req.Context(), tp)
next.ServeHTTP(w, req.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
}
// NewTraceparent generates a new traceparent.
func NewTraceparent() (*tracing.Traceparent, error) {
return tracing.New()
}
// WithTraceparent returns a new context with the given tracing id added to the
// context.
func WithTraceparent(ctx context.Context, tp *tracing.Traceparent) context.Context {
return context.WithValue(ctx, traceheaderKey, tp)
}
// GetTraceparent returns the tracing id from the context if it exists.
func GetTraceparent(ctx context.Context) (*tracing.Traceparent, bool) {
v, ok := ctx.Value(traceheaderKey).(*tracing.Traceparent)
return v, ok
}
// WithName returns a new context with the given name in the context. This name
// will appear in the log entries that include the returning context.
func WithName(ctx context.Context, name string) context.Context {
return context.WithValue(ctx, nameKey, name)
}
// GetName returns the log name from the context if it exists.
func GetName(ctx context.Context) (string, bool) {
v, ok := ctx.Value(nameKey).(string)
return v, ok
}