Files
web/mw/requestid.go
T

49 lines
2.3 KiB
Go

package mw
import (
"net/http"
"code.nochebuena.dev/einherjar/core/logz"
)
// RequestIDFrom injects a per-request ID into the context (via [logz.WithRequestID])
// and the X-Request-ID response header, using the ID that resolve returns for the
// request.
//
// resolve receives the request so the application can decide the ID from it — most
// importantly, to continue a correlation ID a client already sent, so a distributed
// trace survives this boundary. The framework deliberately does not read a header,
// choose a header name, or validate the value: acceptability is per-service. A
// service that persists the ID in a typed column must reject what it cannot store
// and mint its own; a service that only logs an opaque string need not care. Reading
// the header here would accept, on a service's behalf, a value that service may be
// unable to store — so resolution is the application's to own, and generation is
// merely the fallback branch a resolver takes when there is no usable inbound ID.
//
// resolve is called exactly once per request and is expected to return a non-empty
// ID. When it returns "", no ID is attached — the response header is omitted and the
// context carries none — rather than propagating an empty value; supplying a resolver
// that can resolve to "" (e.g. one with no generation fallback) is a caller error.
func RequestIDFrom(resolve func(r *http.Request) string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if id := resolve(r); id != "" {
r = r.WithContext(logz.WithRequestID(r.Context(), id))
w.Header().Set("X-Request-ID", id)
}
next.ServeHTTP(w, r)
})
}
}
// RequestID injects a freshly generated request ID into the context (via
// [logz.WithRequestID]) and sets the X-Request-ID response header. generator is
// called once per request — pass uuid.NewString or a custom function.
//
// It always generates and ignores any inbound X-Request-ID. To continue a
// correlation ID the client supplied, use [RequestIDFrom] with a resolver that
// reads and validates it.
func RequestID(generator func() string) func(http.Handler) http.Handler {
return RequestIDFrom(func(*http.Request) string { return generator() })
}