feat(web): add mw.RequestIDFrom (resolver sees the request); dependency refresh; v1.4.0

This commit is contained in:
2026-08-12 15:27:32 -06:00
parent 929fafcfa5
commit 80b28dfcc4
8 changed files with 202 additions and 39 deletions
+25
View File
@@ -6,6 +6,31 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
---
## [1.4.0] — 2026-08-09
Minor — resolvable request IDs, plus a dependency refresh.
### Added
- **`mw.RequestIDFrom(resolve func(*http.Request) string)`** — the resolver sees the request,
so a service can continue a correlation ID a client already sent (a distributed trace survives
this boundary). The framework provides plumbing only: it does not read a header, choose a header
name, or validate the value — that policy is the application's, because a value the framework
accepts on a service's behalf may be one that service cannot store. Generation becomes the
fallback branch of resolution rather than a separate mode.
### Changed
- `mw.RequestID(generator func() string)` is unchanged in signature and behaviour (always
generates, ignores inbound); it is now expressed as `RequestIDFrom` with a request-ignoring resolver.
- Refreshed dependencies (`go-chi/chi/v5` v5.3.1, `golang.org/x/time` v0.15.0).
- Bumped `contracts`, `core` to v1.4.0.
### Notes
- An empty resolver result attaches no ID (header omitted, context carries none) rather than a
silently-empty value; a resolver that can return "" is a caller error.
## [1.3.0] — 2026-08-08
Minor release carrying a **breaking API change** to CORS configuration. The framework is
+1 -1
View File
@@ -1,6 +1,6 @@
# einherjar/web
[![version](https://img.shields.io/badge/version-v1.3.0-5C4EE5?style=flat-square)](https://code.nochebuena.dev/einherjar/web)
[![version](https://img.shields.io/badge/version-v1.4.0-5C4EE5?style=flat-square)](https://code.nochebuena.dev/einherjar/web)
[![license](https://img.shields.io/badge/license-AGPL--3.0-22863A?style=flat-square)](LICENSE)
[![go](https://img.shields.io/badge/Go-1.26+-00ADD8?style=flat-square&logo=go&logoColor=white)](https://go.dev)
+1
View File
@@ -19,3 +19,4 @@ Decisions worth noting (not ADR-worthy individually):
| UUID v7 for request IDs | v7 with v4 fallback | Time-ordered IDs sort chronologically in logs; fallback ensures generation never fails |
| `observability.Checkable` not redefined | Imported from contracts | Starters implement contracts directly; no web import needed by db/cache starters |
| Background goroutine for in-memory eviction | `time.Ticker` goroutine | Avoids `worker` module dependency; in-memory store is self-contained |
| `mw.RequestIDFrom` resolver sees the request (v1.4.0) | New entry point takes `func(*http.Request) string`; `RequestID` becomes a request-ignoring wrapper over it | An inbound correlation id must be able to survive this boundary, but acceptability is per-service — a typed audit column rejects what an opaque log accepts. The framework provides plumbing only (context + header, once per request); the app owns policy (which header, validation, generation fallback). An empty resolver result attaches nothing rather than a silently-empty value |
+10 -10
View File
@@ -3,20 +3,20 @@ module code.nochebuena.dev/einherjar/web
go 1.26
require (
code.nochebuena.dev/einherjar/contracts v1.3.0
code.nochebuena.dev/einherjar/core v1.3.0
github.com/go-chi/chi/v5 v5.2.1
code.nochebuena.dev/einherjar/contracts v1.4.0
code.nochebuena.dev/einherjar/core v1.4.0
github.com/go-chi/chi/v5 v5.3.1
github.com/google/uuid v1.6.0
golang.org/x/time v0.11.0
golang.org/x/time v0.15.0
)
require (
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
golang.org/x/crypto v0.46.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
github.com/go-playground/validator/v10 v10.30.3 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
)
+20 -20
View File
@@ -1,36 +1,36 @@
code.nochebuena.dev/einherjar/contracts v1.3.0 h1:rm5hqaA1NBtWgH8okwwt6WLoIne1SwQ1Ogi7qbbwfY8=
code.nochebuena.dev/einherjar/contracts v1.3.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
code.nochebuena.dev/einherjar/core v1.3.0 h1:LRT8gln+KJLLGzySVf3C0WX/qiufxg5Jp5v2jySBirE=
code.nochebuena.dev/einherjar/core v1.3.0/go.mod h1:2Pdbb3Pni8dYBZKOpQKqzpR/WFq+Ln9+KSPycf7DQh0=
code.nochebuena.dev/einherjar/contracts v1.4.0 h1:rv/93dGXmXvO90G0uxCu8y3+5+EobkVvcoxh/BywIFk=
code.nochebuena.dev/einherjar/contracts v1.4.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
code.nochebuena.dev/einherjar/core v1.4.0 h1:YBRFzgeWNh8BCHueNYGo+V754BjzvJvq2CddJcc5ZjQ=
code.nochebuena.dev/einherjar/core v1.4.0/go.mod h1:dILfAATF++TBeLOwUTQsYci+Ft7yK5ivt00iRYctfGk=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8=
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+15
View File
@@ -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)
+33 -7
View File
@@ -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)
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() })
}
+96
View File
@@ -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)
}
}