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.
This commit is contained in:
rcourtman
2025-10-21 11:37:57 +00:00
parent 407e7168d9
commit 5c0d760d54

View File

@@ -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)