Files
coder/coderd/httpmw/requestid.go
T
Spike Curtis 49b34a716a fix: fix slog to always use array of Fields (#21426)
Upgrades to slog v3 which includes a small, but backward incompatible API change to the acceptible call arguments when logging. This change allows us to verify via compile time type checking that arguments are correct and won't cause a panic, as was possible in slog v1, which this replaces (v2 was tagged but never used in coder/coder).

It also updates dependencies that also use slog and were updated.

I've left the `aibridge` dependency as a commit SHA, under the assumption that the team there (cc @pawbana @dannykopping ) will tag and update the dependency soon and on their own schedule.

Other dependencies, I pushed new tags.
2026-01-08 10:29:41 +04:00

41 lines
996 B
Go

package httpmw
import (
"context"
"net/http"
"github.com/google/uuid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"cdr.dev/slog/v3"
)
type requestIDContextKey struct{}
// RequestID returns the ID of the request.
func RequestID(r *http.Request) uuid.UUID {
rid, ok := r.Context().Value(requestIDContextKey{}).(uuid.UUID)
if !ok {
panic("developer error: request id middleware not provided")
}
return rid
}
// 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()
ridString := rid.String()
ctx := context.WithValue(r.Context(), requestIDContextKey{}, rid)
ctx = slog.With(ctx, slog.F("request_id", rid))
trace.SpanFromContext(ctx).
SetAttributes(attribute.String("request_id", rid.String()))
rw.Header().Set("X-Coder-Request-Id", ridString)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}