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:
parent
cdbc6057b0
commit
59cd456428
1 changed files with 9 additions and 3 deletions
|
|
@ -7,8 +7,10 @@ import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/rcourtman/pulse-go-rewrite/internal/logging"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -42,8 +44,14 @@ func ErrorHandler(next http.Handler) http.Handler {
|
||||||
return
|
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
|
// Create a custom response writer to capture status codes
|
||||||
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
||||||
|
rw.Header().Set("X-Request-ID", requestID)
|
||||||
|
|
||||||
// Recover from panics
|
// Recover from panics
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|
@ -52,6 +60,7 @@ func ErrorHandler(next http.Handler) http.Handler {
|
||||||
Interface("error", err).
|
Interface("error", err).
|
||||||
Str("path", r.URL.Path).
|
Str("path", r.URL.Path).
|
||||||
Str("method", r.Method).
|
Str("method", r.Method).
|
||||||
|
Str("request_id", requestID).
|
||||||
Bytes("stack", debug.Stack()).
|
Bytes("stack", debug.Stack()).
|
||||||
Msg("Panic recovered in API handler")
|
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
|
// Call the next handler
|
||||||
next.ServeHTTP(rw, r)
|
next.ServeHTTP(rw, r)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue