Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
929fafcfa5
|
||
|
|
c611e67946
|
||
|
|
fc3fe750d4
|
||
|
|
8876af3bfa
|
||
|
|
c6a753e49b
|
||
|
|
f0ff3c38ed
|
+94
-5
@@ -6,13 +6,102 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## [1.0.1] — 2026-05-28
|
## [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
|
### Changed
|
||||||
|
|
||||||
- Bumped `code.nochebuena.dev/einherjar/contracts` dependency from v1.0.0 to v1.1.0.
|
- Bumped `contracts`, `core` to v1.3.0.
|
||||||
No code changes — MVS selects v1.1.0 automatically when a consumer (e.g. `auth`)
|
|
||||||
requires the new `SecurityBag` API. This pin makes the minimum explicit.
|
## [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
|
||||||
|
(which finally makes the previously-drafted `contracts` v1.1.0 pin real).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Package doc examples didn't compile.** Verified by compiling the example patterns
|
||||||
|
against the real API:
|
||||||
|
- `mw.Recover()` -> `mw.Recover(logger)` — the recover middleware takes a `logging.Logger`
|
||||||
|
(`server`, `mw` package docs and `server.go`).
|
||||||
|
- `health.NewHandler(logger, …)` -> `health.NewHandler(logger, …).ServeHTTP` — the handler
|
||||||
|
returns `http.Handler`, but chi's `Get` takes `http.HandlerFunc`; same for
|
||||||
|
`NewHandlerWithConfig` (`server`, `web`, `health` package docs).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Bumped `contracts` and `core` to v1.1.0 (framework version alignment).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -50,7 +139,7 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
|
|||||||
request logging: method, path, status, latency; uses `StatusRecorder` to capture code
|
request logging: method, path, status, latency; uses `StatusRecorder` to capture code
|
||||||
- `CORS(origins []string) func(http.Handler) http.Handler` — sets
|
- `CORS(origins []string) func(http.Handler) http.Handler` — sets
|
||||||
`Access-Control-Allow-Origin` for listed origins; supports preflight (`OPTIONS`)
|
`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)`;
|
- `RateLimiterStore` interface — `Allow(ctx context.Context, key string) (bool, error)`;
|
||||||
pluggable backend; `error` return allows infrastructure failures to surface; fail-open
|
pluggable backend; `error` return allows infrastructure failures to surface; fail-open
|
||||||
contract: non-nil error allows the request
|
contract: non-nil error allows the request
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# einherjar/web
|
# einherjar/web
|
||||||
|
|
||||||
[](https://code.nochebuena.dev/einherjar/web)
|
[](https://code.nochebuena.dev/einherjar/web)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
[](https://go.dev)
|
[](https://go.dev)
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ logger := logz.New(logz.Config{JSON: true, StaticArgs: []any{"service", "api"}})
|
|||||||
srv := web.New(logger)
|
srv := web.New(logger)
|
||||||
// Pre-wired stack: Recover → RequestID (UUID v7/v4) → RequestLogger → [CORS]
|
// 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 := launcher.New(logger)
|
||||||
lc.Append(srv)
|
lc.Append(srv)
|
||||||
@@ -57,12 +57,16 @@ lc.BeforeStart(func() error {
|
|||||||
lc.Run()
|
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
|
```go
|
||||||
srv := web.New(logger, web.Config{
|
srv := web.New(logger, web.Config{
|
||||||
Server: server.Config{Port: 9090},
|
Server: server.Config{
|
||||||
AllowedOrigins: []string{"https://example.com"},
|
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_WRITE_TIMEOUT` | `10s` | HTTP write timeout |
|
||||||
| `EINHERJAR_SERVER_IDLE_TIMEOUT` | `120s` | Keep-alive idle timeout |
|
| `EINHERJAR_SERVER_IDLE_TIMEOUT` | `120s` | Keep-alive idle timeout |
|
||||||
| `EINHERJAR_SERVER_SHUTDOWN_TIMEOUT` | `10s` | Graceful shutdown budget |
|
| `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`)
|
### Tier 2 — Full control (`server.New`)
|
||||||
|
|
||||||
@@ -90,9 +94,9 @@ import (
|
|||||||
|
|
||||||
srv := server.New(logger, server.Config{Port: 9090},
|
srv := server.New(logger, server.Config{Port: 9090},
|
||||||
server.WithMiddleware(
|
server.WithMiddleware(
|
||||||
mw.Recover(),
|
mw.Recover(logger),
|
||||||
mw.RequestID(myIDGenerator),
|
mw.RequestID(myIDGenerator),
|
||||||
mw.CORS([]string{"*"}),
|
mw.CORS([]string{"https://example.com"}),
|
||||||
mw.RequestLogger(logger),
|
mw.RequestLogger(logger),
|
||||||
myOwnMiddleware,
|
myOwnMiddleware,
|
||||||
),
|
),
|
||||||
@@ -177,7 +181,7 @@ values are mapped to their canonical HTTP status codes (full 16-code table below
|
|||||||
import "code.nochebuena.dev/einherjar/web/health"
|
import "code.nochebuena.dev/einherjar/web/health"
|
||||||
|
|
||||||
// db and cache implement observability.Checkable
|
// 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:
|
// Response shape:
|
||||||
// {"status":"UP","components":{"db":{"status":"UP","latency":"1.2ms"}}}
|
// {"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/httputil] — typed handler adapters and HTTP response helpers
|
||||||
// - [code.nochebuena.dev/einherjar/web/health] — concurrent health check handler
|
// - [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})
|
// logger := logz.New(logz.Config{JSON: true})
|
||||||
// lc := launcher.New(logger)
|
// lc := launcher.New(logger)
|
||||||
//
|
//
|
||||||
// srv := web.New(logger)
|
// // CORS from EINHERJAR_SERVER_CORS_ORIGINS (explicit origins; empty ⇒ CORS off + log).
|
||||||
// srv.Get("/health", health.NewHandler(logger, db, cache))
|
// srv := web.New(logger, web.Config{Server: cfg.Server})
|
||||||
|
// srv.Get("/health", health.NewHandler(logger, db, cache).ServeHTTP)
|
||||||
//
|
//
|
||||||
// lc.Append(srv)
|
// lc.Append(srv)
|
||||||
// lc.BeforeStart(func() error {
|
|
||||||
// // register routes
|
|
||||||
// return nil
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// if err := lc.Run(); err != nil {
|
// if err := lc.Run(); err != nil {
|
||||||
// logger.Error("launcher failed", err)
|
// logger.Error("launcher failed", err)
|
||||||
// os.Exit(1)
|
// 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
|
package web
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ module code.nochebuena.dev/einherjar/web
|
|||||||
go 1.26
|
go 1.26
|
||||||
|
|
||||||
require (
|
require (
|
||||||
code.nochebuena.dev/einherjar/contracts v1.0.0
|
code.nochebuena.dev/einherjar/contracts v1.3.0
|
||||||
code.nochebuena.dev/einherjar/core v1.0.0
|
code.nochebuena.dev/einherjar/core v1.3.0
|
||||||
github.com/go-chi/chi/v5 v5.2.1
|
github.com/go-chi/chi/v5 v5.2.1
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
golang.org/x/time v0.11.0
|
golang.org/x/time v0.11.0
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
code.nochebuena.dev/einherjar/contracts v1.0.0 h1:hRudEtOIqU7vwedYLsCh8+9q5dCnKb61qX+zibqImRU=
|
code.nochebuena.dev/einherjar/contracts v1.3.0 h1:rm5hqaA1NBtWgH8okwwt6WLoIne1SwQ1Ogi7qbbwfY8=
|
||||||
code.nochebuena.dev/einherjar/contracts v1.0.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
code.nochebuena.dev/einherjar/contracts v1.3.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
||||||
code.nochebuena.dev/einherjar/core v1.0.0 h1:AueZgfjp3+rQmDKOxmJQ945TTh+sqC1l/xJdTOdbr9w=
|
code.nochebuena.dev/einherjar/core v1.3.0 h1:LRT8gln+KJLLGzySVf3C0WX/qiufxg5Jp5v2jySBirE=
|
||||||
code.nochebuena.dev/einherjar/core v1.0.0/go.mod h1:0IywfRnJXX9xXQO6iPVaq2QDlXbbpXrB8A4T7gO8nE4=
|
code.nochebuena.dev/einherjar/core v1.3.0/go.mod h1:2Pdbb3Pni8dYBZKOpQKqzpR/WFq+Ln9+KSPycf7DQh0=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
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/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 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
|
|||||||
+2
-2
@@ -12,12 +12,12 @@
|
|||||||
//
|
//
|
||||||
// # Example
|
// # Example
|
||||||
//
|
//
|
||||||
// srv.Get("/health", health.NewHandler(logger, db, cache, storage))
|
// srv.Get("/health", health.NewHandler(logger, db, cache, storage).ServeHTTP)
|
||||||
//
|
//
|
||||||
// Or with custom timeout:
|
// Or with custom timeout:
|
||||||
//
|
//
|
||||||
// srv.Get("/health", health.NewHandlerWithConfig(logger,
|
// srv.Get("/health", health.NewHandlerWithConfig(logger,
|
||||||
// health.Config{CheckTimeout: 3 * time.Second},
|
// health.Config{CheckTimeout: 3 * time.Second},
|
||||||
// db, cache,
|
// db, cache,
|
||||||
// ))
|
// ).ServeHTTP)
|
||||||
package health
|
package health
|
||||||
|
|||||||
+28
-5
@@ -7,10 +7,29 @@ const (
|
|||||||
allowedHeaders = "Content-Type, Authorization, X-Request-ID"
|
allowedHeaders = "Content-Type, Authorization, X-Request-ID"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CORS sets cross-origin resource sharing headers for the provided origins.
|
// CORS sets cross-origin resource sharing headers for the provided origins
|
||||||
// Returns 204 No Content for OPTIONS preflight requests.
|
// (exact match; an empty slice is a no-op). Returns 204 No Content for OPTIONS
|
||||||
// Pass the outermost origins first; an empty slice is a no-op.
|
// 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 {
|
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))
|
originSet := make(map[string]struct{}, len(origins))
|
||||||
for _, o := range origins {
|
for _, o := range origins {
|
||||||
originSet[o] = struct{}{}
|
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.
|
// CORSAllowAll allows any origin by reflecting the request Origin (it does not set
|
||||||
// Use only in development — never in production.
|
// 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 {
|
func CORSAllowAll() func(http.Handler) http.Handler {
|
||||||
return func(next http.Handler) http.Handler {
|
return func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// # Recommended middleware order (outermost first)
|
// # Recommended middleware order (outermost first)
|
||||||
//
|
//
|
||||||
// server.WithMiddleware(
|
// server.WithMiddleware(
|
||||||
// mw.Recover(),
|
// mw.Recover(logger),
|
||||||
// mw.RequestID(uuid.NewString),
|
// mw.RequestID(uuid.NewString),
|
||||||
// mw.RequestLogger(logger),
|
// mw.RequestLogger(logger),
|
||||||
// mw.CORS([]string{"https://example.com"}),
|
// mw.CORS([]string{"https://example.com"}),
|
||||||
|
|||||||
@@ -11,6 +11,12 @@ type Config struct {
|
|||||||
WriteTimeout time.Duration `env:"EINHERJAR_SERVER_WRITE_TIMEOUT" envDefault:"10s"`
|
WriteTimeout time.Duration `env:"EINHERJAR_SERVER_WRITE_TIMEOUT" envDefault:"10s"`
|
||||||
IdleTimeout time.Duration `env:"EINHERJAR_SERVER_IDLE_TIMEOUT" envDefault:"120s"`
|
IdleTimeout time.Duration `env:"EINHERJAR_SERVER_IDLE_TIMEOUT" envDefault:"120s"`
|
||||||
ShutdownTimeout time.Duration `env:"EINHERJAR_SERVER_SHUTDOWN_TIMEOUT" envDefault:"10s"`
|
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
|
const defaultShutdownTimeout = 10 * time.Second
|
||||||
|
|||||||
+18
-5
@@ -4,22 +4,35 @@
|
|||||||
// directly into [launcher.New] and exposes the full chi routing API.
|
// directly into [launcher.New] and exposes the full chi routing API.
|
||||||
//
|
//
|
||||||
// For the happy path use [web.New], which pre-wires the recommended middleware
|
// For the happy path use [web.New], which pre-wires the recommended middleware
|
||||||
// stack. Use this package directly when you need explicit control over
|
// stack (explicit-origin CORS included). Use this package directly when you need
|
||||||
// middleware order, a custom request-ID generator, or any other deviation from
|
// explicit control over middleware order, a custom request-ID generator, or
|
||||||
// the defaults.
|
// 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
|
// # Basic usage
|
||||||
//
|
//
|
||||||
// srv := server.New(logger, server.Config{Port: 8080},
|
// srv := server.New(logger, server.Config{Port: 8080},
|
||||||
// server.WithMiddleware(
|
// server.WithMiddleware(
|
||||||
// mw.Recover(),
|
// mw.Recover(logger),
|
||||||
// mw.RequestID(myIDGenerator),
|
// mw.RequestID(myIDGenerator),
|
||||||
// mw.RequestLogger(logger),
|
// mw.RequestLogger(logger),
|
||||||
// mw.CORS([]string{"https://example.com"}),
|
// mw.CORS([]string{"https://example.com"}),
|
||||||
// ),
|
// ),
|
||||||
// )
|
// )
|
||||||
//
|
//
|
||||||
// srv.Get("/health", health.NewHandler(logger, db))
|
// srv.Get("/health", health.NewHandler(logger, db).ServeHTTP)
|
||||||
//
|
//
|
||||||
// lc := launcher.New(logger)
|
// lc := launcher.New(logger)
|
||||||
// lc.Append(srv)
|
// lc.Append(srv)
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
//
|
//
|
||||||
// srv := server.New(logger, server.Config{Port: 8080},
|
// srv := server.New(logger, server.Config{Port: 8080},
|
||||||
// server.WithMiddleware(
|
// server.WithMiddleware(
|
||||||
// mw.Recover(),
|
// mw.Recover(logger),
|
||||||
// mw.RequestID(uuid.NewString),
|
// mw.RequestID(uuid.NewString),
|
||||||
// mw.RequestLogger(logger),
|
// mw.RequestLogger(logger),
|
||||||
// ),
|
// ),
|
||||||
|
|||||||
@@ -10,21 +10,24 @@ import (
|
|||||||
"code.nochebuena.dev/einherjar/web/server"
|
"code.nochebuena.dev/einherjar/web/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config aggregates configuration for the web module.
|
// Config aggregates configuration for the web module. Server holds the HTTP server
|
||||||
// Server holds HTTP server settings; all fields carry caarlos0/env struct tags.
|
// settings, including the single source of truth for CORS: Server.CORSOrigins,
|
||||||
// AllowedOrigins is programmatic-only — set it directly or via the env tag.
|
// 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 {
|
type Config struct {
|
||||||
Server server.Config
|
Server server.Config
|
||||||
AllowedOrigins []string `env:"EINHERJAR_SERVER_CORS_ORIGINS" envSeparator:","`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a [server.Server] with the recommended middleware stack pre-applied:
|
// New creates a [server.Server] with the recommended middleware stack pre-applied:
|
||||||
// 1. Recover — catches panics, returns 500
|
// 1. Recover — catches panics, returns 500
|
||||||
// 2. RequestID — injects UUID v7 request ID (falls back to v4)
|
// 2. RequestID — injects UUID v7 request ID (falls back to v4)
|
||||||
// 3. RequestLogger — logs method, path, status, latency
|
// 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 {
|
func New(logger logging.Logger, cfg ...Config) server.Server {
|
||||||
var c Config
|
var c Config
|
||||||
if len(cfg) > 0 {
|
if len(cfg) > 0 {
|
||||||
@@ -36,8 +39,10 @@ func New(logger logging.Logger, cfg ...Config) server.Server {
|
|||||||
mw.RequestID(newRequestID),
|
mw.RequestID(newRequestID),
|
||||||
mw.RequestLogger(logger),
|
mw.RequestLogger(logger),
|
||||||
}
|
}
|
||||||
if len(c.AllowedOrigins) > 0 {
|
if len(c.Server.CORSOrigins) > 0 {
|
||||||
middleware = append(middleware, mw.CORS(c.AllowedOrigins))
|
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...))
|
return server.New(logger, c.Server, server.WithMiddleware(middleware...))
|
||||||
|
|||||||
Reference in New Issue
Block a user