2022-09-02 13:04:29 -05:00
|
|
|
package httpmw
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2023-10-09 14:05:10 -05:00
|
|
|
"go.opentelemetry.io/otel/attribute"
|
|
|
|
|
"go.opentelemetry.io/otel/trace"
|
2022-09-02 13:04:29 -05:00
|
|
|
|
2026-01-08 10:29:41 +04:00
|
|
|
"cdr.dev/slog/v3"
|
2022-09-02 13:04:29 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type requestIDContextKey struct{}
|
|
|
|
|
|
|
|
|
|
// RequestID returns the ID of the request.
|
|
|
|
|
func RequestID(r *http.Request) uuid.UUID {
|
2026-02-27 11:50:56 -05:00
|
|
|
rid, ok := RequestIDOptional(r)
|
2022-09-02 13:04:29 -05:00
|
|
|
if !ok {
|
|
|
|
|
panic("developer error: request id middleware not provided")
|
|
|
|
|
}
|
|
|
|
|
return rid
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-27 11:50:56 -05:00
|
|
|
// RequestIDOptional returns the request ID when present.
|
|
|
|
|
func RequestIDOptional(r *http.Request) (uuid.UUID, bool) {
|
|
|
|
|
rid, ok := r.Context().Value(requestIDContextKey{}).(uuid.UUID)
|
|
|
|
|
return rid, ok
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WithRequestID stores a request ID in the context.
|
|
|
|
|
func WithRequestID(ctx context.Context, rid uuid.UUID) context.Context {
|
|
|
|
|
return context.WithValue(ctx, requestIDContextKey{}, rid)
|
|
|
|
|
}
|
|
|
|
|
|
2022-09-02 13:04:29 -05:00
|
|
|
// AttachRequestID adds a request ID to each HTTP request.
|
|
|
|
|
func AttachRequestID(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
|
rid := uuid.New()
|
2022-09-21 17:07:00 -05:00
|
|
|
ridString := rid.String()
|
2022-09-02 13:04:29 -05:00
|
|
|
|
|
|
|
|
ctx := context.WithValue(r.Context(), requestIDContextKey{}, rid)
|
|
|
|
|
ctx = slog.With(ctx, slog.F("request_id", rid))
|
|
|
|
|
|
2023-10-09 14:05:10 -05:00
|
|
|
trace.SpanFromContext(ctx).
|
|
|
|
|
SetAttributes(attribute.String("request_id", rid.String()))
|
|
|
|
|
|
2022-09-21 17:07:00 -05:00
|
|
|
rw.Header().Set("X-Coder-Request-Id", ridString)
|
2022-09-02 13:04:29 -05:00
|
|
|
next.ServeHTTP(rw, r.WithContext(ctx))
|
|
|
|
|
})
|
|
|
|
|
}
|