feat(web): move CORSOrigins to server.Config; web.New warns on empty CORS; align to v1.2.0

This commit is contained in:
2026-08-08 02:24:08 -06:00
parent fc3fe750d4
commit c611e67946
8 changed files with 94 additions and 24 deletions
+17
View File
@@ -6,6 +6,23 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
--- ---
## [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 ## [1.1.3] — 2026-08-08
Patch — CORS documentation discoverability. Patch — CORS documentation discoverability.
+1 -1
View File
@@ -1,6 +1,6 @@
# einherjar/web # einherjar/web
[![version](https://img.shields.io/badge/version-v1.1.3-5C4EE5?style=flat-square)](https://code.nochebuena.dev/einherjar/web) [![version](https://img.shields.io/badge/version-v1.2.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) [![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) [![go](https://img.shields.io/badge/Go-1.26+-00ADD8?style=flat-square&logo=go&logoColor=white)](https://go.dev)
+31 -7
View File
@@ -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 := web.New(logger, web.Config{Server: cfg.Server})
// srv.Get("/health", health.NewHandler(logger, db, cache).ServeHTTP) // 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
+2 -2
View File
@@ -3,8 +3,8 @@ module code.nochebuena.dev/einherjar/web
go 1.26 go 1.26
require ( require (
code.nochebuena.dev/einherjar/contracts v1.1.3 code.nochebuena.dev/einherjar/contracts v1.2.0
code.nochebuena.dev/einherjar/core v1.1.3 code.nochebuena.dev/einherjar/core v1.2.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
+4 -4
View File
@@ -1,7 +1,7 @@
code.nochebuena.dev/einherjar/contracts v1.1.3 h1:rBtQUVCeqaIKMcG1+R0ndHM/4cRm3XTFnVNzFTbf1QU= code.nochebuena.dev/einherjar/contracts v1.2.0 h1:i1qschvttqXJTd7yaFmHkvtj4weGfTcTkj8q9sG6pRI=
code.nochebuena.dev/einherjar/contracts v1.1.3/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI= code.nochebuena.dev/einherjar/contracts v1.2.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
code.nochebuena.dev/einherjar/core v1.1.3 h1:MjWUA/hJ5IOosACh0in9xzFZ7jc1TTO0YEHh1xQVuOg= code.nochebuena.dev/einherjar/core v1.2.0 h1:nomXS05rqY9bOwnXhLbCIK/K8/KW3WbLOMp4gR8ho/4=
code.nochebuena.dev/einherjar/core v1.1.3/go.mod h1:xkI2uQ4S0FQHbFiawTUFgJdG5jbivcZpGFddHxQe8Q0= code.nochebuena.dev/einherjar/core v1.2.0/go.mod h1:L5PNjnuNN7vz057egI5y3r8DIGr7ZrbACFU19jgWoWY=
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=
+6
View File
@@ -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
+16 -3
View File
@@ -4,9 +4,22 @@
// 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
// //
+17 -7
View File
@@ -10,21 +10,25 @@ 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 CORS origins (Server.CORSOrigins, loaded from
// AllowedOrigins is programmatic-only — set it directly or via the env tag. // EINHERJAR_SERVER_CORS_ORIGINS). AllowedOrigins is a programmatic-only override —
// set it in code to override Server.CORSOrigins; leave it nil to use the env value.
type Config struct { type Config struct {
Server server.Config Server server.Config
AllowedOrigins []string `env:"EINHERJAR_SERVER_CORS_ORIGINS" envSeparator:","` AllowedOrigins []string // code-only override of Server.CORSOrigins (no env tag)
} }
// 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 origins are configured (Server.CORSOrigins from
// EINHERJAR_SERVER_CORS_ORIGINS, or the AllowedOrigins code override)
// //
// 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 +40,14 @@ func New(logger logging.Logger, cfg ...Config) server.Server {
mw.RequestID(newRequestID), mw.RequestID(newRequestID),
mw.RequestLogger(logger), mw.RequestLogger(logger),
} }
origins := c.Server.CORSOrigins
if len(c.AllowedOrigins) > 0 { if len(c.AllowedOrigins) > 0 {
middleware = append(middleware, mw.CORS(c.AllowedOrigins)) origins = c.AllowedOrigins
}
if len(origins) > 0 {
middleware = append(middleware, mw.CORS(origins))
} 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...))