package web import ( "net/http" "github.com/google/uuid" "code.nochebuena.dev/einherjar/contracts/logging" "code.nochebuena.dev/einherjar/web/mw" "code.nochebuena.dev/einherjar/web/server" ) // 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 // 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 origins are configured (Server.CORSOrigins from // EINHERJAR_SERVER_CORS_ORIGINS, or the AllowedOrigins code override) // // 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 { c = cfg[0] } middleware := []func(http.Handler) http.Handler{ mw.Recover(logger), mw.RequestID(newRequestID), mw.RequestLogger(logger), } origins := c.Server.CORSOrigins if len(c.AllowedOrigins) > 0 { 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...)) } func newRequestID() string { id, err := uuid.NewV7() if err != nil { return uuid.NewString() } return id.String() }