This commit is contained in:
Arpan Saha 2025-12-05 11:04:00 -05:00 committed by GitHub
commit 17aaae1f72
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 2 deletions

View file

@ -3,6 +3,7 @@ package tracing
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@ -121,6 +122,11 @@ func TestTracing_ServeHTTP_Propagation_Without_Initial_Headers(t *testing.T) {
if err := ot.ServeHTTP(w, req, handler); err != nil {
t.Errorf("ServeHTTP error: %v", err)
}
responseTraceParent := w.Header().Get("Traceparent")
if responseTraceParent == "" {
t.Errorf("Missing traceparent in response headers")
}
}
func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) {
@ -128,13 +134,14 @@ func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) {
SpanName: "mySpan",
}
dummyTraceParentPrefix := "00-11111111111111111111111111111111"
req := createRequestWithContext("GET", "https://example.com/foo")
req.Header.Set("traceparent", "00-11111111111111111111111111111111-1111111111111111-01")
req.Header.Set("traceparent", fmt.Sprintf("%s-1111111111111111-01", dummyTraceParentPrefix))
w := httptest.NewRecorder()
var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error {
traceparent := request.Header.Get("Traceparent")
if !strings.HasPrefix(traceparent, "00-11111111111111111111111111111111") {
if !strings.HasPrefix(traceparent, dummyTraceParentPrefix) {
t.Errorf("Invalid traceparent: %v", traceparent)
}
@ -152,6 +159,17 @@ func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) {
if err := ot.ServeHTTP(w, req, handler); err != nil {
t.Errorf("ServeHTTP error: %v", err)
}
responseTraceParent := w.Header().Get("Traceparent")
if responseTraceParent == "" {
t.Error("Missing traceparent in response headers")
} else if !strings.HasPrefix(responseTraceParent, dummyTraceParentPrefix) {
t.Errorf(
"Traceparent prefix in response headers (%s) not same as initial (%s)",
responseTraceParent,
dummyTraceParentPrefix,
)
}
}
func TestTracing_ServeHTTP_Next_Error(t *testing.T) {

View file

@ -93,6 +93,8 @@ func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request
caddyhttp.SetVar(ctx, "trace_id", traceID)
// Add a span_id placeholder, accessible via `{http.vars.span_id}`.
caddyhttp.SetVar(ctx, "span_id", spanID)
// Add traceId and spanId to response headers
w.Header().Set("traceparent", fmt.Sprintf("00-%s-%s-01", traceID, spanID))
// Add the traceID and spanID to the log fields for the request.
if extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok {
extra.Add(zap.String("traceID", traceID))