feat(web): add mw.RequestIDFrom (resolver sees the request); dependency refresh; v1.4.0
This commit is contained in:
@@ -12,6 +12,21 @@
|
||||
// mw.CORS([]string{"https://example.com"}),
|
||||
// )
|
||||
//
|
||||
// # Request IDs
|
||||
//
|
||||
// [RequestID] always generates a fresh ID. To continue a correlation ID a client
|
||||
// already sent — so a distributed trace survives this boundary — use [RequestIDFrom]
|
||||
// and read the ID off the request in your resolver. The framework does not read the
|
||||
// header or validate the value: what is acceptable is per-service (a typed audit
|
||||
// column rejects what an opaque log accepts), so that policy stays with the caller.
|
||||
//
|
||||
// mw.RequestIDFrom(func(r *http.Request) string {
|
||||
// if id, err := uuid.Parse(r.Header.Get("X-Request-ID")); err == nil {
|
||||
// return id.String() // continue the client's id
|
||||
// }
|
||||
// return uuid.NewString() // otherwise mint one
|
||||
// })
|
||||
//
|
||||
// # Rate limiting
|
||||
//
|
||||
// // In-memory (default — no extra dependencies)
|
||||
|
||||
+34
-8
@@ -6,17 +6,43 @@ import (
|
||||
"code.nochebuena.dev/einherjar/core/logz"
|
||||
)
|
||||
|
||||
// RequestID injects a unique 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.
|
||||
func RequestID(generator func() string) func(http.Handler) http.Handler {
|
||||
// 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) {
|
||||
id := generator()
|
||||
ctx := logz.WithRequestID(r.Context(), id)
|
||||
r = r.WithContext(ctx)
|
||||
w.Header().Set("X-Request-ID", id)
|
||||
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() })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package mw
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"code.nochebuena.dev/einherjar/core/logz"
|
||||
)
|
||||
|
||||
// A resolver that continues the client's X-Request-ID lands in both the context
|
||||
// and the response header.
|
||||
func TestRequestIDFrom_HonoursInbound(t *testing.T) {
|
||||
const inbound = "client-supplied-123"
|
||||
|
||||
var ctxID string
|
||||
h := RequestIDFrom(func(r *http.Request) string {
|
||||
return r.Header.Get("X-Request-ID")
|
||||
})(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
ctxID = logz.GetRequestID(r.Context())
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.Header.Set("X-Request-ID", inbound)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if ctxID != inbound {
|
||||
t.Errorf("context request id = %q, want %q", ctxID, inbound)
|
||||
}
|
||||
if got := rec.Header().Get("X-Request-ID"); got != inbound {
|
||||
t.Errorf("response header = %q, want %q", got, inbound)
|
||||
}
|
||||
}
|
||||
|
||||
// Deliberate regression: RequestID(gen) always generates and never honours an
|
||||
// inbound X-Request-ID. Callers that want to continue a client id use RequestIDFrom.
|
||||
func TestRequestID_AlwaysGenerates_IgnoresInbound(t *testing.T) {
|
||||
const inbound = "client-supplied-123"
|
||||
const generated = "generated-999"
|
||||
|
||||
var ctxID string
|
||||
h := RequestID(func() string { return generated })(
|
||||
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
ctxID = logz.GetRequestID(r.Context())
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.Header.Set("X-Request-ID", inbound)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if ctxID != generated {
|
||||
t.Errorf("context request id = %q, want generated %q (inbound must be ignored)", ctxID, generated)
|
||||
}
|
||||
if got := rec.Header().Get("X-Request-ID"); got != generated {
|
||||
t.Errorf("response header = %q, want %q", got, generated)
|
||||
}
|
||||
}
|
||||
|
||||
// The resolver runs exactly once per request.
|
||||
func TestRequestIDFrom_ResolverCalledOnce(t *testing.T) {
|
||||
calls := 0
|
||||
h := RequestIDFrom(func(*http.Request) string {
|
||||
calls++
|
||||
return "id"
|
||||
})(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
|
||||
if calls != 1 {
|
||||
t.Errorf("resolver called %d times, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// An empty resolver result attaches nothing: no context id and no response header,
|
||||
// rather than a silently-empty value.
|
||||
func TestRequestIDFrom_EmptyResult_AttachesNothing(t *testing.T) {
|
||||
var ctxID string
|
||||
h := RequestIDFrom(func(*http.Request) string { return "" })(
|
||||
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
ctxID = logz.GetRequestID(r.Context())
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.Header.Set("X-Request-ID", "should-be-ignored")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if ctxID != "" {
|
||||
t.Errorf("context request id = %q, want empty (nothing attached)", ctxID)
|
||||
}
|
||||
if vals := rec.Header().Values("X-Request-ID"); len(vals) != 0 {
|
||||
t.Errorf("X-Request-ID header = %v on empty resolve; want absent", vals)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user