Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcccfef443
|
||
|
|
80b28dfcc4
|
||
|
|
929fafcfa5
|
||
|
|
c611e67946
|
||
|
|
fc3fe750d4
|
||
|
|
8876af3bfa
|
||
|
|
c6a753e49b
|
+125
-1
@@ -6,6 +6,130 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
|
||||
|
||||
---
|
||||
|
||||
## [1.5.0] — 2026-08-09
|
||||
|
||||
Minor — configurable success status on the httputil handler adapters.
|
||||
|
||||
### Added
|
||||
|
||||
- **`httputil.WithStatus(code int) Option`** and variadic `opts ...Option` on `Handle`,
|
||||
`HandleNoBody` and `HandleEmpty`. Override the success status — e.g. `WithStatus(201)` on a
|
||||
resource-creating POST, `WithStatus(202)` on an async `HandleEmpty`. Non-breaking: existing
|
||||
calls keep their defaults (200 / 200 / 204).
|
||||
|
||||
### Changed
|
||||
|
||||
- Bumped `contracts`, `core` to v1.5.0.
|
||||
|
||||
### Notes
|
||||
|
||||
- `WithStatus` is success-only: the adapters own only the happy path, so the code must be 2xx.
|
||||
A non-2xx code panics at wiring (the service fails to boot) rather than emitting a wrong
|
||||
status at runtime. Error status stays separate — resolved from the returned xerror by `Error`.
|
||||
|
||||
## [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
|
||||
private with controlled consumers, so this ships in the 1.x line with a loud compile break
|
||||
instead of a v2 module-path (`/v2`) migration.
|
||||
|
||||
### Removed
|
||||
|
||||
- **⚠️ BREAKING: `web.Config.AllowedOrigins` removed.** CORS origins now have a single
|
||||
home: `server.Config.CORSOrigins` (env `EINHERJAR_SERVER_CORS_ORIGINS`). The field was
|
||||
env-backed through v1.1.x and a code-only override in v1.2.0 — reading it after the env
|
||||
tag moved silently served *no* CORS. Removing it turns that runtime trap into a compile
|
||||
error.
|
||||
|
||||
**Migration:** replace `cfg.Web.AllowedOrigins` with `cfg.Server.CORSOrigins`, and
|
||||
`web.Config{AllowedOrigins: o}` with `web.Config{Server: server.Config{CORSOrigins: o}}`
|
||||
— or just let `web.New` read `EINHERJAR_SERVER_CORS_ORIGINS`. The MCP flags any leftover
|
||||
reference (`validate_snippet` rule `web.allowedorigins-removed`).
|
||||
|
||||
### Changed
|
||||
|
||||
- Bumped `contracts`, `core` to v1.3.0.
|
||||
|
||||
## [1.2.0] — 2026-08-08
|
||||
|
||||
Minor — CORS configuration moved to its rightful struct; `web.New` made safe-by-default.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`CORSOrigins` now lives on `server.Config`** (env var `EINHERJAR_SERVER_CORS_ORIGINS`), the
|
||||
struct its name advertises — it previously loaded into `web.Config`. `web.Config.AllowedOrigins`
|
||||
remains as a code-only override (no env tag). Wiring via `web.New` or the env var is unaffected.
|
||||
- Bumped `contracts`, `core` to v1.2.0.
|
||||
|
||||
### Added
|
||||
|
||||
- `web.New` logs a warning when no CORS origins are configured, instead of silently disabling CORS.
|
||||
- Package docs (`web`, `web/server`) document when to use `web.New` vs `server.New`, with compiling
|
||||
examples and the env-gated allow-all CORS convention.
|
||||
|
||||
## [1.1.3] — 2026-08-08
|
||||
|
||||
Patch — CORS documentation discoverability.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `mw.CORS` and `CORSAllowAll` doc comments now document the `"*"` rejection (panic) and the
|
||||
env-gated CORS convention (`local -> CORSAllowAll`, else `mw.CORS(origins)`), so `search_symbols`
|
||||
surfaces it — previously the convention lived only in code comments and the wire example.
|
||||
|
||||
### Changed
|
||||
|
||||
- Bumped `contracts`, `core` to v1.1.3.
|
||||
|
||||
## [1.1.2] — 2026-08-08
|
||||
|
||||
Patch — CORS wildcard hardening plus documentation fixes.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`mw.CORS` now rejects `"*"` (panics at construction)** instead of silently no-op'ing it.
|
||||
`"*"` matched nothing (exact-match only), so a service passing it ran with CORS effectively
|
||||
off — a silent trap. Fail loud at boot; use `mw.CORSAllowAll()` (development) or list explicit origins.
|
||||
- Bumped `contracts`, `core` to v1.1.2.
|
||||
|
||||
### Fixed
|
||||
|
||||
- README Go examples now compile: `mw.Recover(logger)`, `health.NewHandler(...).ServeHTTP`, and the
|
||||
`mw.CORS` example no longer passes `"*"`. Corrected the `CORSAllowAll` description.
|
||||
|
||||
## [1.1.1] — 2026-08-07
|
||||
|
||||
Patch — coordinated framework version alignment.
|
||||
|
||||
### Changed
|
||||
|
||||
- Bumped `contracts` and `core` to v1.1.1 (framework version alignment). No code or API changes.
|
||||
|
||||
## [1.1.0] — 2026-08-07
|
||||
|
||||
Coordinated framework release. Documentation fixes plus the framework version bump
|
||||
@@ -61,7 +185,7 @@ Coordinated framework release. Documentation fixes plus the framework version bu
|
||||
request logging: method, path, status, latency; uses `StatusRecorder` to capture code
|
||||
- `CORS(origins []string) func(http.Handler) http.Handler` — sets
|
||||
`Access-Control-Allow-Origin` for listed origins; supports preflight (`OPTIONS`)
|
||||
- `CORSAllowAll() func(http.Handler) http.Handler` — shorthand for `CORS([]string{"*"})`
|
||||
- `CORSAllowAll() func(http.Handler) http.Handler` — allows any origin by reflecting the request `Origin` (no `Access-Control-Allow-Credentials`); development only
|
||||
- `RateLimiterStore` interface — `Allow(ctx context.Context, key string) (bool, error)`;
|
||||
pluggable backend; `error` return allows infrastructure failures to surface; fail-open
|
||||
contract: non-nil error allows the request
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# einherjar/web
|
||||
|
||||
[](https://code.nochebuena.dev/einherjar/web)
|
||||
[](https://code.nochebuena.dev/einherjar/web)
|
||||
[](LICENSE)
|
||||
[](https://go.dev)
|
||||
|
||||
@@ -46,7 +46,7 @@ logger := logz.New(logz.Config{JSON: true, StaticArgs: []any{"service", "api"}})
|
||||
srv := web.New(logger)
|
||||
// Pre-wired stack: Recover → RequestID (UUID v7/v4) → RequestLogger → [CORS]
|
||||
|
||||
srv.Get("/health", health.NewHandler(logger, db, cache))
|
||||
srv.Get("/health", health.NewHandler(logger, db, cache).ServeHTTP)
|
||||
|
||||
lc := launcher.New(logger)
|
||||
lc.Append(srv)
|
||||
@@ -57,12 +57,16 @@ lc.BeforeStart(func() error {
|
||||
lc.Run()
|
||||
```
|
||||
|
||||
With origins (CORS auto-applied):
|
||||
With origins set in code (CORS auto-applied). `Server.CORSOrigins` is the single
|
||||
source of truth — normally it loads from `EINHERJAR_SERVER_CORS_ORIGINS`, but you
|
||||
can set it directly to override without the env var:
|
||||
|
||||
```go
|
||||
srv := web.New(logger, web.Config{
|
||||
Server: server.Config{Port: 9090},
|
||||
AllowedOrigins: []string{"https://example.com"},
|
||||
Server: server.Config{
|
||||
Port: 9090,
|
||||
CORSOrigins: []string{"https://example.com"},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
@@ -76,7 +80,7 @@ Environment variables for `web.New`:
|
||||
| `EINHERJAR_SERVER_WRITE_TIMEOUT` | `10s` | HTTP write timeout |
|
||||
| `EINHERJAR_SERVER_IDLE_TIMEOUT` | `120s` | Keep-alive idle timeout |
|
||||
| `EINHERJAR_SERVER_SHUTDOWN_TIMEOUT` | `10s` | Graceful shutdown budget |
|
||||
| `EINHERJAR_SERVER_CORS_ORIGINS` | _(empty — CORS off)_ | Comma-separated allowed origins |
|
||||
| `EINHERJAR_SERVER_CORS_ORIGINS` | _(empty — CORS off)_ | Comma-separated allowed origins (`*` is rejected — use `mw.CORSAllowAll()` in code for allow-all) |
|
||||
|
||||
### Tier 2 — Full control (`server.New`)
|
||||
|
||||
@@ -90,9 +94,9 @@ import (
|
||||
|
||||
srv := server.New(logger, server.Config{Port: 9090},
|
||||
server.WithMiddleware(
|
||||
mw.Recover(),
|
||||
mw.Recover(logger),
|
||||
mw.RequestID(myIDGenerator),
|
||||
mw.CORS([]string{"*"}),
|
||||
mw.CORS([]string{"https://example.com"}),
|
||||
mw.RequestLogger(logger),
|
||||
myOwnMiddleware,
|
||||
),
|
||||
@@ -146,26 +150,33 @@ type CreateUserRes struct {
|
||||
|
||||
v := valid.New()
|
||||
|
||||
// POST /users — decode body → validate → call service → encode response
|
||||
srv.Post("/users", httputil.Handle(v, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) {
|
||||
// POST /users — decode → validate → call → encode. WithStatus makes it 201 Created.
|
||||
srv.Post("/users", httputil.Handle(v, logger, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) {
|
||||
id, err := userService.Create(ctx, req.Email, req.Name)
|
||||
if err != nil {
|
||||
return CreateUserRes{}, err
|
||||
}
|
||||
return CreateUserRes{ID: id}, nil
|
||||
}))
|
||||
}, httputil.WithStatus(http.StatusCreated)))
|
||||
|
||||
// GET /users/{id} — no request body
|
||||
srv.Get("/users/{id}", httputil.HandleNoBody(func(ctx context.Context) (CreateUserRes, error) {
|
||||
// GET /users/{id} — no request body (defaults to 200)
|
||||
srv.Get("/users/{id}", httputil.HandleNoBody(logger, func(ctx context.Context) (CreateUserRes, error) {
|
||||
// ...
|
||||
}))
|
||||
|
||||
// DELETE /users/{id} — no response body
|
||||
srv.Delete("/users/{id}", httputil.HandleEmpty(v, func(ctx context.Context, req DeleteReq) error {
|
||||
// DELETE /users/{id} — no response body (defaults to 204)
|
||||
srv.Delete("/users/{id}", httputil.HandleEmpty(v, logger, func(ctx context.Context, req DeleteReq) error {
|
||||
return userService.Delete(ctx, req.ID)
|
||||
}))
|
||||
```
|
||||
|
||||
**Success status** defaults to 200 for the body-returning adapters and 204 for `HandleEmpty`;
|
||||
override it with `httputil.WithStatus(code)` — e.g. `WithStatus(http.StatusCreated)` on a POST, or
|
||||
`WithStatus(http.StatusAccepted)` for an async `HandleEmpty`. The code must be 2xx (these adapters
|
||||
own only the success path); a non-2xx code panics at wiring, so the service fails to start rather
|
||||
than emit a wrong status at runtime. **Error status is separate** — return the right `*xerrors.Err`
|
||||
and `Error` maps it (full 16-code table below).
|
||||
|
||||
Validation failures return 400 with a structured JSON error. All `*xerrors.Err`
|
||||
values are mapped to their canonical HTTP status codes (full 16-code table below).
|
||||
|
||||
@@ -177,7 +188,7 @@ values are mapped to their canonical HTTP status codes (full 16-code table below
|
||||
import "code.nochebuena.dev/einherjar/web/health"
|
||||
|
||||
// db and cache implement observability.Checkable
|
||||
srv.Get("/health", health.NewHandler(logger, db, cache))
|
||||
srv.Get("/health", health.NewHandler(logger, db, cache).ServeHTTP)
|
||||
|
||||
// Response shape:
|
||||
// {"status":"UP","components":{"db":{"status":"UP","latency":"1.2ms"}}}
|
||||
|
||||
@@ -12,22 +12,46 @@
|
||||
// - [code.nochebuena.dev/einherjar/web/httputil] — typed handler adapters and HTTP response helpers
|
||||
// - [code.nochebuena.dev/einherjar/web/health] — concurrent health check handler
|
||||
//
|
||||
// # Happy path
|
||||
// # Choosing web.New vs server.New
|
||||
//
|
||||
// Two tiers over the same underlying server:
|
||||
//
|
||||
// - [New] (web.New) — batteries-included. The recommended middleware stack is wired
|
||||
// for you; CORS uses explicit origins from EINHERJAR_SERVER_CORS_ORIGINS. Use it for
|
||||
// most services. It does NOT support allow-all CORS.
|
||||
// - [code.nochebuena.dev/einherjar/web/server.New] — full control. You compose the
|
||||
// middleware list yourself. Use it when you need a custom middleware order, a custom
|
||||
// request-ID generator, or allow-all CORS in development ([mw.CORSAllowAll], gated by
|
||||
// environment).
|
||||
//
|
||||
// # web.New — batteries included (explicit CORS origins)
|
||||
//
|
||||
// logger := logz.New(logz.Config{JSON: true})
|
||||
// lc := launcher.New(logger)
|
||||
//
|
||||
// srv := web.New(logger)
|
||||
// // CORS from EINHERJAR_SERVER_CORS_ORIGINS (explicit origins; empty ⇒ CORS off + log).
|
||||
// srv := web.New(logger, web.Config{Server: cfg.Server})
|
||||
// srv.Get("/health", health.NewHandler(logger, db, cache).ServeHTTP)
|
||||
//
|
||||
// lc.Append(srv)
|
||||
// lc.BeforeStart(func() error {
|
||||
// // register routes
|
||||
// return nil
|
||||
// })
|
||||
//
|
||||
// if err := lc.Run(); err != nil {
|
||||
// logger.Error("launcher failed", err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
//
|
||||
// # server.New — full control (allow-all CORS in dev)
|
||||
//
|
||||
// For allow-all CORS in local development, gate it by environment and compose the
|
||||
// stack yourself. mw.CORS panics on "*", so allow-all is [mw.CORSAllowAll], never a
|
||||
// "*" in the origins list:
|
||||
//
|
||||
// var corsMW func(http.Handler) http.Handler
|
||||
// if strings.EqualFold(cfg.AppEnv, "local") {
|
||||
// corsMW = mw.CORSAllowAll() // dev: any origin
|
||||
// } else {
|
||||
// corsMW = mw.CORS(cfg.Server.CORSOrigins) // prod: explicit origins from env
|
||||
// }
|
||||
// srv := server.New(logger, cfg.Server, server.WithMiddleware(
|
||||
// mw.Recover(logger), mw.RequestID(uuid.NewString), corsMW, mw.RequestLogger(logger),
|
||||
// ))
|
||||
package web
|
||||
|
||||
@@ -19,3 +19,5 @@ 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 |
|
||||
| `httputil` success status is configurable (v1.5.0) | `Handle`/`HandleNoBody`/`HandleEmpty` take `opts ...Option`; `WithStatus(code)` overrides the default (200 / 200 / 204) | 201 Created / 202 Accepted are common and were only reachable by hand-rolling the handler (losing decode+validate+error-mapping). Variadic options are non-breaking and future-extensible (headers, etc.). `WithStatus` is success-only (2xx) and panics at wiring on a non-2xx code — a wrong status is a routing mistake that should fail to boot, not surface at runtime; error status stays separate, resolved from the xerror by `Error` |
|
||||
|
||||
@@ -3,20 +3,20 @@ module code.nochebuena.dev/einherjar/web
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
code.nochebuena.dev/einherjar/contracts v1.1.0
|
||||
code.nochebuena.dev/einherjar/core v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.2.1
|
||||
code.nochebuena.dev/einherjar/contracts v1.5.0
|
||||
code.nochebuena.dev/einherjar/core v1.5.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
|
||||
)
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
code.nochebuena.dev/einherjar/contracts v1.1.0 h1:GsGr6reyrd9qCc7D8CqbT1LWPTeeK9lT4r4EdsNA5Ro=
|
||||
code.nochebuena.dev/einherjar/contracts v1.1.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
||||
code.nochebuena.dev/einherjar/core v1.1.0 h1:zxj9bFPthEEFRnvWV/vgNZqWa2y/kAo3p5pODWablyk=
|
||||
code.nochebuena.dev/einherjar/core v1.1.0/go.mod h1:Ot2JbjsnZ33Ed5C9Ev1kSn2PW+F4dLz/LRwIUh+fYt0=
|
||||
code.nochebuena.dev/einherjar/contracts v1.5.0 h1:vDlpLXtVZ4Q4l3AR02qLQhnKnEDq2vE8+mydwg85hUU=
|
||||
code.nochebuena.dev/einherjar/contracts v1.5.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
||||
code.nochebuena.dev/einherjar/core v1.5.0 h1:LXVyHaite+NHL8LIGj/NvCVqgCrkpVMfm2VaIZ9aAU8=
|
||||
code.nochebuena.dev/einherjar/core v1.5.0/go.mod h1:lxiRdCVLl1/XnbCsHbeZJIFNXZ29QaSl2lMGZm3CQjM=
|
||||
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=
|
||||
|
||||
+16
-9
@@ -14,9 +14,11 @@ import (
|
||||
// - Decodes the JSON request body into Req.
|
||||
// - Validates Req using the provided [valid.Validator].
|
||||
// - Calls fn with the request context and decoded Req.
|
||||
// - Encodes Res as JSON with HTTP 200 on success.
|
||||
// - Encodes Res as JSON on success — HTTP 200 by default, or the code given via
|
||||
// [WithStatus] (e.g. WithStatus(http.StatusCreated) for a resource-creating POST).
|
||||
// - On error: logs via [Error] (level derived from HTTP status) and writes the standardized JSON body.
|
||||
func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) (Res, error)) http.HandlerFunc {
|
||||
func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) (Res, error), opts ...Option) http.HandlerFunc {
|
||||
status := resolveStatus(http.StatusOK, opts)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req Req
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
@@ -32,28 +34,33 @@ func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusOK, res)
|
||||
JSON(w, status, res)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleNoBody adapts a typed function with no request body (GET, HEAD).
|
||||
// Calls fn with the request context; encodes the result as JSON with HTTP 200.
|
||||
// Calls fn with the request context; encodes the result as JSON — HTTP 200 by
|
||||
// default, or the code given via [WithStatus].
|
||||
// On error: logs via [Error] and writes the standardized JSON body.
|
||||
func HandleNoBody[Res any](logger logging.Logger, fn func(ctx context.Context) (Res, error)) http.HandlerFunc {
|
||||
func HandleNoBody[Res any](logger logging.Logger, fn func(ctx context.Context) (Res, error), opts ...Option) http.HandlerFunc {
|
||||
status := resolveStatus(http.StatusOK, opts)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
res, err := fn(r.Context())
|
||||
if err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusOK, res)
|
||||
JSON(w, status, res)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleEmpty adapts a typed function with a request body but no response body.
|
||||
// Decodes and validates Req, calls fn, returns 204 No Content on success.
|
||||
// Decodes and validates Req, calls fn, and writes a body-less success — 204 No
|
||||
// Content by default, or the code given via [WithStatus] (e.g.
|
||||
// WithStatus(http.StatusAccepted) for async processing).
|
||||
// On error: logs via [Error] and writes the standardized JSON body.
|
||||
func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) error) http.HandlerFunc {
|
||||
func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) error, opts ...Option) http.HandlerFunc {
|
||||
status := resolveStatus(http.StatusNoContent, opts)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req Req
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
@@ -68,6 +75,6 @@ func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
NoContent(w)
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package httputil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/core/logz"
|
||||
"code.nochebuena.dev/einherjar/core/valid"
|
||||
)
|
||||
|
||||
type tReq struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
}
|
||||
type tRes struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func discardLogger() logging.Logger { return logz.New(logz.Config{Writer: io.Discard}) }
|
||||
|
||||
// Default: Handle writes 200 with the JSON payload (regression — no opts).
|
||||
func TestHandle_Default200(t *testing.T) {
|
||||
h := Handle(valid.New(), discardLogger(), func(context.Context, tReq) (tRes, error) {
|
||||
return tRes{ID: "x"}, nil
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if got := strings.TrimSpace(rec.Body.String()); got != `{"id":"x"}` {
|
||||
t.Errorf("body = %q, want {\"id\":\"x\"}", got)
|
||||
}
|
||||
}
|
||||
|
||||
// WithStatus(201) makes a resource-creating Handle return 201 Created + the body.
|
||||
func TestHandle_WithStatusCreated(t *testing.T) {
|
||||
h := Handle(valid.New(), discardLogger(), func(context.Context, tReq) (tRes, error) {
|
||||
return tRes{ID: "x"}, nil
|
||||
}, WithStatus(http.StatusCreated))
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201", rec.Code)
|
||||
}
|
||||
if got := strings.TrimSpace(rec.Body.String()); got != `{"id":"x"}` {
|
||||
t.Errorf("body = %q, want the payload", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleNoBody_WithStatus(t *testing.T) {
|
||||
h := HandleNoBody(discardLogger(), func(context.Context) (tRes, error) {
|
||||
return tRes{ID: "y"}, nil
|
||||
}, WithStatus(http.StatusAccepted))
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Default: HandleEmpty writes 204 with no body.
|
||||
func TestHandleEmpty_Default204(t *testing.T) {
|
||||
h := HandleEmpty(valid.New(), discardLogger(), func(context.Context, tReq) error { return nil })
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204", rec.Code)
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Errorf("expected empty body, got %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// WithStatus on a body-less adapter changes the code but keeps the empty body.
|
||||
func TestHandleEmpty_WithStatusAccepted_NoBody(t *testing.T) {
|
||||
h := HandleEmpty(valid.New(), discardLogger(), func(context.Context, tReq) error { return nil }, WithStatus(http.StatusAccepted))
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Errorf("expected empty body, got %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// A non-2xx code is a wiring mistake: WithStatus panics at construction so the
|
||||
// service fails to boot rather than emitting a wrong status at request time.
|
||||
func TestWithStatus_PanicsOnNon2xx(t *testing.T) {
|
||||
for _, code := range []int{0, 100, 199, 300, 404, 500, 1000} {
|
||||
func() {
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Errorf("WithStatus(%d) did not panic", code)
|
||||
}
|
||||
}()
|
||||
_ = WithStatus(code)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithStatus_Allows2xx(t *testing.T) {
|
||||
for _, code := range []int{200, 201, 202, 204, 299} {
|
||||
func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Errorf("WithStatus(%d) panicked: %v", code, r)
|
||||
}
|
||||
}()
|
||||
_ = WithStatus(code)
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package httputil
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Option configures a Handle* adapter. With no options each adapter writes its
|
||||
// default success status (200 for the body-returning adapters, 204 for
|
||||
// [HandleEmpty]). Options are applied once at wiring time, not per request.
|
||||
type Option func(*options)
|
||||
|
||||
type options struct {
|
||||
status int
|
||||
}
|
||||
|
||||
// WithStatus overrides the success status an adapter writes — e.g.
|
||||
// WithStatus(http.StatusCreated) for a POST that creates a resource, or
|
||||
// WithStatus(http.StatusAccepted) for an async [HandleEmpty].
|
||||
//
|
||||
// It exists because the Handle* adapters own only the happy path: they always
|
||||
// write a success response, so the status is theirs to set, while error statuses
|
||||
// are derived separately from the returned xerror by [Error]. The code must
|
||||
// therefore be 2xx — anything else is a routing mistake, since an error status
|
||||
// never belongs on the success path. WithStatus panics on a non-2xx code, and
|
||||
// because routes are wired at startup that panic surfaces at boot: the service
|
||||
// fails to start rather than emitting a wrong status at request time. (mw.Recover
|
||||
// guards requests, so it does not catch a wiring-time panic — which is the point.)
|
||||
func WithStatus(code int) Option {
|
||||
if code < 200 || code > 299 {
|
||||
panic(fmt.Sprintf("httputil.WithStatus: success status must be 2xx, got %d", code))
|
||||
}
|
||||
return func(o *options) { o.status = code }
|
||||
}
|
||||
|
||||
// resolveStatus folds opts over the adapter's default success status.
|
||||
func resolveStatus(def int, opts []Option) int {
|
||||
o := options{status: def}
|
||||
for _, opt := range opts {
|
||||
opt(&o)
|
||||
}
|
||||
return o.status
|
||||
}
|
||||
+28
-5
@@ -7,10 +7,29 @@ const (
|
||||
allowedHeaders = "Content-Type, Authorization, X-Request-ID"
|
||||
)
|
||||
|
||||
// CORS sets cross-origin resource sharing headers for the provided origins.
|
||||
// Returns 204 No Content for OPTIONS preflight requests.
|
||||
// Pass the outermost origins first; an empty slice is a no-op.
|
||||
// CORS sets cross-origin resource sharing headers for the provided origins
|
||||
// (exact match; an empty slice is a no-op). Returns 204 No Content for OPTIONS
|
||||
// preflight requests.
|
||||
//
|
||||
// It panics on "*": a wildcard matches no real Origin here, so passing it would
|
||||
// silently disable CORS. For allow-all use [CORSAllowAll] (development only). The
|
||||
// recommended wiring gates CORS by environment:
|
||||
//
|
||||
// var corsMW func(http.Handler) http.Handler
|
||||
// if strings.EqualFold(cfg.AppEnv, "local") {
|
||||
// corsMW = mw.CORSAllowAll() // dev: any origin
|
||||
// } else {
|
||||
// corsMW = mw.CORS(cfg.CORSOrigins) // prod: explicit origins
|
||||
// }
|
||||
func CORS(origins []string) func(http.Handler) http.Handler {
|
||||
// "*" would be a silent no-op (exact-match only) — reject it loudly so a
|
||||
// misconfigured service fails to boot instead of quietly blocking browsers.
|
||||
for _, o := range origins {
|
||||
if o == "*" {
|
||||
panic(`mw.CORS: "*" is not a valid origin — list explicit origins, or use CORSAllowAll() for allow-all`)
|
||||
}
|
||||
}
|
||||
|
||||
originSet := make(map[string]struct{}, len(origins))
|
||||
for _, o := range origins {
|
||||
originSet[o] = struct{}{}
|
||||
@@ -37,8 +56,12 @@ func CORS(origins []string) func(http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
|
||||
// CORSAllowAll is a convenience wrapper that allows any origin.
|
||||
// Use only in development — never in production.
|
||||
// CORSAllowAll allows any origin by reflecting the request Origin (it does not set
|
||||
// Access-Control-Allow-Credentials). Development only — never in production.
|
||||
//
|
||||
// Use it for the local branch of the env-gated CORS convention; use [CORS] with
|
||||
// explicit origins everywhere else. Because [CORS] panics on "*", CORSAllowAll — not
|
||||
// a "*" in the origins list — is the way to allow all.
|
||||
func CORSAllowAll() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -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
@@ -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() })
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,12 @@ type Config struct {
|
||||
WriteTimeout time.Duration `env:"EINHERJAR_SERVER_WRITE_TIMEOUT" envDefault:"10s"`
|
||||
IdleTimeout time.Duration `env:"EINHERJAR_SERVER_IDLE_TIMEOUT" envDefault:"120s"`
|
||||
ShutdownTimeout time.Duration `env:"EINHERJAR_SERVER_SHUTDOWN_TIMEOUT" envDefault:"10s"`
|
||||
|
||||
// CORSOrigins is the allowed cross-origin list (comma-separated in the env var).
|
||||
// web.New applies mw.CORS with it automatically; callers of server.New pass it to
|
||||
// mw.CORS themselves. "*" is rejected by mw.CORS — use mw.CORSAllowAll for allow-all
|
||||
// (development only).
|
||||
CORSOrigins []string `env:"EINHERJAR_SERVER_CORS_ORIGINS" envSeparator:","`
|
||||
}
|
||||
|
||||
const defaultShutdownTimeout = 10 * time.Second
|
||||
|
||||
+16
-3
@@ -4,9 +4,22 @@
|
||||
// directly into [launcher.New] and exposes the full chi routing API.
|
||||
//
|
||||
// For the happy path use [web.New], which pre-wires the recommended middleware
|
||||
// stack. Use this package directly when you need explicit control over
|
||||
// middleware order, a custom request-ID generator, or any other deviation from
|
||||
// the defaults.
|
||||
// stack (explicit-origin CORS included). Use this package directly when you need
|
||||
// explicit control over middleware order, a custom request-ID generator, or
|
||||
// allow-all CORS in development.
|
||||
//
|
||||
// # CORS
|
||||
//
|
||||
// [Config.CORSOrigins] loads EINHERJAR_SERVER_CORS_ORIGINS. Gate allow-all by
|
||||
// environment — mw.CORS panics on "*", so allow-all is [mw.CORSAllowAll], never a
|
||||
// wildcard origin:
|
||||
//
|
||||
// var corsMW func(http.Handler) http.Handler
|
||||
// if strings.EqualFold(cfg.AppEnv, "local") {
|
||||
// corsMW = mw.CORSAllowAll() // dev: any origin
|
||||
// } else {
|
||||
// corsMW = mw.CORS(cfg.Server.CORSOrigins) // prod: explicit origins
|
||||
// }
|
||||
//
|
||||
// # Basic usage
|
||||
//
|
||||
|
||||
@@ -10,21 +10,24 @@ import (
|
||||
"code.nochebuena.dev/einherjar/web/server"
|
||||
)
|
||||
|
||||
// Config aggregates configuration for the web module.
|
||||
// Server holds HTTP server settings; all fields carry caarlos0/env struct tags.
|
||||
// AllowedOrigins is programmatic-only — set it directly or via the env tag.
|
||||
// Config aggregates configuration for the web module. Server holds the HTTP server
|
||||
// settings, including the single source of truth for CORS: Server.CORSOrigins,
|
||||
// loaded from EINHERJAR_SERVER_CORS_ORIGINS. To override origins from code (without
|
||||
// the env var), set Server.CORSOrigins directly before calling New.
|
||||
type Config struct {
|
||||
Server server.Config
|
||||
AllowedOrigins []string `env:"EINHERJAR_SERVER_CORS_ORIGINS" envSeparator:","`
|
||||
}
|
||||
|
||||
// New creates a [server.Server] with the recommended middleware stack pre-applied:
|
||||
// 1. Recover — catches panics, returns 500
|
||||
// 2. RequestID — injects UUID v7 request ID (falls back to v4)
|
||||
// 3. RequestLogger — logs method, path, status, latency
|
||||
// 4. CORS — applied only when cfg.AllowedOrigins is non-empty
|
||||
// 4. CORS — applied only when Server.CORSOrigins is non-empty (from
|
||||
// EINHERJAR_SERVER_CORS_ORIGINS, or set in code before calling New)
|
||||
//
|
||||
// For full control over middleware composition use [server.New] directly.
|
||||
// web.New uses explicit origins only; it does NOT support allow-all. For
|
||||
// [mw.CORSAllowAll] (development) or any custom middleware order, use [server.New]
|
||||
// directly. When no origins are configured, CORS is off and a log line records it.
|
||||
func New(logger logging.Logger, cfg ...Config) server.Server {
|
||||
var c Config
|
||||
if len(cfg) > 0 {
|
||||
@@ -36,8 +39,10 @@ func New(logger logging.Logger, cfg ...Config) server.Server {
|
||||
mw.RequestID(newRequestID),
|
||||
mw.RequestLogger(logger),
|
||||
}
|
||||
if len(c.AllowedOrigins) > 0 {
|
||||
middleware = append(middleware, mw.CORS(c.AllowedOrigins))
|
||||
if len(c.Server.CORSOrigins) > 0 {
|
||||
middleware = append(middleware, mw.CORS(c.Server.CORSOrigins))
|
||||
} else {
|
||||
logger.Info("web.New: no CORS origins configured (EINHERJAR_SERVER_CORS_ORIGINS) — cross-origin browser requests will be blocked")
|
||||
}
|
||||
|
||||
return server.New(logger, c.Server, server.WithMiddleware(middleware...))
|
||||
|
||||
Reference in New Issue
Block a user