Files

49 lines
1.5 KiB
Go

// Package middleware contains cross-cutting HTTP middleware (request_id, logging, recovery, etc.).
package middleware
import (
"context"
"crypto/rand"
"net/http"
"github.com/oklog/ulid/v2"
)
// ctxKey is an unexported type used to scope context keys to this package and
// prevent collisions with keys defined by other packages.
type ctxKey int
const requestIDKey ctxKey = 1
// RequestID is HTTP middleware that ensures every request carries a stable
// identifier propagated through the request context and the X-Request-ID
// response header.
//
// Behaviour:
// - If the incoming request has X-Client-Request-ID set, that value is
// trusted and reused (allowing clients to correlate retries).
// - Otherwise a fresh ULID is generated using crypto/rand as the entropy
// source so the value is unguessable and time-ordered.
//
// Downstream handlers can retrieve the value via RequestIDFromContext.
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Client-Request-ID")
if id == "" {
id = ulid.MustNew(ulid.Now(), rand.Reader).String()
}
w.Header().Set("X-Request-ID", id)
ctx := context.WithValue(r.Context(), requestIDKey, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// RequestIDFromContext returns the request ID stored in ctx by the RequestID
// middleware, or an empty string if none is present.
func RequestIDFromContext(ctx context.Context) string {
if v, ok := ctx.Value(requestIDKey).(string); ok {
return v
}
return ""
}