-
Notifications
You must be signed in to change notification settings - Fork 14
/
traceability.go
55 lines (43 loc) · 1.4 KB
/
traceability.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
package common
import (
"context"
"net/http"
"github.com/anz-bank/sysl-go/common/internal"
"github.com/anz-bank/pkg/log"
"github.com/google/uuid"
)
type traceabilityContextKey struct{}
type requestID struct {
id uuid.UUID
wasProvided bool
}
const traceIDLogField = "traceid"
// Injects a traceId UUID into the request context.
func TraceabilityMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
val, err := uuid.Parse(r.Header.Get("RequestID"))
if err != nil {
log.Info(internal.InitFieldsFromRequest(r).Onto(ctx), "Incoming request with invalid or missing RequestID header, filled traceid with new UUID instead")
r = r.WithContext(AddTraceIDToContext(r.Context(), uuid.New(), false))
} else {
r = r.WithContext(AddTraceIDToContext(r.Context(), val, true))
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func GetTraceIDFromContext(ctx context.Context) uuid.UUID {
val, _ := TryGetTraceIDFromContext(ctx)
return val
}
func TryGetTraceIDFromContext(ctx context.Context) (uuid.UUID, bool) {
val, ok := ctx.Value(traceabilityContextKey{}).(*requestID)
if ok {
return val.id, val.wasProvided
}
return uuid.New(), false
}
func AddTraceIDToContext(ctx context.Context, id uuid.UUID, wasProvided bool) context.Context {
return context.WithValue(ctx, traceabilityContextKey{}, &requestID{id, wasProvided})
}