github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/middleware/debug_trace.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 6 "go.opencensus.io/plugin/ochttp/propagation/b3" 7 "go.opencensus.io/trace" 8 "go.opencensus.io/trace/propagation" 9 ) 10 11 const ( 12 // DebugTraceHeader is the header key used for detecting if 13 // trace should be force sampled and returned in the response 14 DebugTraceHeader = "X-Debug-Trace" 15 ) 16 17 // DebugTrace is a middleware that allows debugging requests by providing the Trace ID 18 // back to the caller in the same header in the response 19 func DebugTrace(format propagation.HTTPFormat, key string) func(handler http.Handler) http.Handler { 20 return func(handler http.Handler) http.Handler { 21 if format == nil { 22 format = &b3.HTTPFormat{} 23 } 24 25 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 26 debugHeader := r.Header.Get(DebugTraceHeader) 27 if debugHeader == key { 28 ctx, span := trace.StartSpan(r.Context(), DebugTraceHeader, trace.WithSampler(trace.AlwaysSample())) 29 r = r.WithContext(ctx) 30 format.SpanContextToRequest(span.SpanContext(), r) 31 w.Header().Add(DebugTraceHeader, span.SpanContext().TraceID.String()) 32 } 33 34 handler.ServeHTTP(w, r) 35 }) 36 } 37 }