feat(http/mw): request id middleware with context propagation

This commit is contained in:
2026-04-28 15:04:00 +08:00
parent 98c9ce139f
commit 5bd56de013
4 changed files with 89 additions and 0 deletions
@@ -0,0 +1,48 @@
// 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 ""
}
@@ -0,0 +1,37 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestRequestID_GeneratesWhenAbsent(t *testing.T) {
var seen string
h := RequestID(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
seen = RequestIDFromContext(r.Context())
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
require.NotEmpty(t, seen)
require.Equal(t, seen, rec.Header().Get("X-Request-ID"))
}
func TestRequestID_PreservesClientHeader(t *testing.T) {
const given = "client-supplied-id"
var seen string
h := RequestID(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
seen = RequestIDFromContext(r.Context())
}))
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("X-Client-Request-ID", given)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
require.Equal(t, given, seen)
require.Equal(t, given, rec.Header().Get("X-Request-ID"))
}