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 -7
View File
@@ -10,21 +10,25 @@ 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 CORS origins (Server.CORSOrigins, loaded from
// 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 {
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:
// 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 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 {
var c Config
if len(cfg) > 0 {
@@ -36,8 +40,14 @@ func New(logger logging.Logger, cfg ...Config) server.Server {
mw.RequestID(newRequestID),
mw.RequestLogger(logger),
}
origins := c.Server.CORSOrigins
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...))