// Package middleware contains chi-compatible HTTP middleware for the server. package middleware import ( "context" "net/http" "github.com/google/uuid" ) type ctxKey string // RequestIDKey is the context key under which the request ID is stored. const RequestIDKey ctxKey = "request_id" // RequestID propagates an X-Request-ID header through the request, generating // a UUID when the client didn't send one. The header is always echoed back. func RequestID(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { id := r.Header.Get("X-Request-ID") if id == "" { id = uuid.NewString() } ctx := context.WithValue(r.Context(), RequestIDKey, id) w.Header().Set("X-Request-ID", id) next.ServeHTTP(w, r.WithContext(ctx)) }) } // GetRequestID returns the request ID stored in ctx, or "" if absent. func GetRequestID(ctx context.Context) string { if id, ok := ctx.Value(RequestIDKey).(string); ok { return id } return "" }