From 5c0d760d5437d79a8ef0b9120f66ea3e3a2d7f7a Mon Sep 17 00:00:00 2001 From: rcourtman Date: Tue, 21 Oct 2025 11:37:57 +0000 Subject: [PATCH] feat: improve request ID handling in middleware Enhance request ID middleware to support distributed tracing: - Honor incoming X-Request-ID headers from upstream proxies/load balancers - Use logging.WithRequestID() for consistent ID generation across codebase - Return X-Request-ID in response headers for client correlation - Include request_id in panic recovery logs for debugging This enables better request tracing across multiple Pulse instances and integrates with standard distributed tracing practices. --- internal/api/middleware.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/internal/api/middleware.go b/internal/api/middleware.go index 5ad3dc4fd..46a546c6a 100644 --- a/internal/api/middleware.go +++ b/internal/api/middleware.go @@ -7,8 +7,10 @@ import ( "net" "net/http" "runtime/debug" + "strings" "time" + "github.com/rcourtman/pulse-go-rewrite/internal/logging" "github.com/rs/zerolog/log" ) @@ -42,8 +44,14 @@ func ErrorHandler(next http.Handler) http.Handler { return } + // Add request ID to context, honoring any incoming header value. + incomingID := strings.TrimSpace(r.Header.Get("X-Request-ID")) + ctxWithID, requestID := logging.WithRequestID(r.Context(), incomingID) + r = r.WithContext(ctxWithID) + // Create a custom response writer to capture status codes rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK} + rw.Header().Set("X-Request-ID", requestID) // Recover from panics defer func() { @@ -52,6 +60,7 @@ func ErrorHandler(next http.Handler) http.Handler { Interface("error", err). Str("path", r.URL.Path). Str("method", r.Method). + Str("request_id", requestID). Bytes("stack", debug.Stack()). Msg("Panic recovered in API handler") @@ -60,9 +69,6 @@ func ErrorHandler(next http.Handler) http.Handler { } }() - // Add request ID to context - requestID := fmt.Sprintf("%d", time.Now().UnixNano()) - // Call the next handler next.ServeHTTP(rw, r)