docs(web): document CORS wildcard rejection + env-gated convention; align to v1.1.3

This commit is contained in:
2026-08-08 01:26:17 -06:00
parent 8876af3bfa
commit fc3fe750d4
5 changed files with 43 additions and 15 deletions
+22 -8
View File
@@ -7,13 +7,23 @@ 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.AllowedOrigins) // prod: explicit origins
// }
func CORS(origins []string) func(http.Handler) http.Handler {
// "*" is a silent no-op here (exact-match only) — reject it loudly at
// construction so a misconfigured service fails to boot instead of quietly
// blocking every browser. For allow-all, call CORSAllowAll (development only).
// "*" 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`)
@@ -46,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) {