46 lines
1.1 KiB
Go

package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
)
// requestIDKey is the context key for request ID
type requestIDKey struct{}
// RequestIDHeader is the HTTP header for request ID
const RequestIDHeader = "X-Request-ID"
// RequestID middleware generates a unique ID for each request
func RequestID() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if request already has an ID
requestID := r.Header.Get(RequestIDHeader)
if requestID == "" {
// Generate a new UUID for the request if not present
requestID = uuid.New().String()
}
// Add request ID to response headers
w.Header().Set(RequestIDHeader, requestID)
// Store request ID in context
ctx := context.WithValue(r.Context(), requestIDKey{}, requestID)
// Call next handler with updated context
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetRequestID retrieves the request ID from context
func GetRequestID(ctx context.Context) string {
if id, ok := ctx.Value(requestIDKey{}).(string); ok {
return id
}
return ""
}