Files
wehub-resource-sync a06f331eb8
CI / benchmark (push) Has been skipped
install-script / posix-syntax (push) Successful in 6m1s
CI / build-onnx (push) Failing after 6m43s
init-smoke / dry-run (push) Failing after 15m57s
security / govulncheck (push) Has been cancelled
security / trivy-fs (push) Has been cancelled
CI / test (1.26, ubuntu-latest) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
CI / test (1.26, macos-latest) (push) Has been cancelled
CI / build-windows (push) Has been cancelled
CI / lint (push) Has been cancelled
install-script / powershell-syntax (push) Has been cancelled
install-script / install (macos-14) (push) Has been cancelled
install-script / install (ubuntu-latest) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:33:42 +08:00

48 lines
1.2 KiB
Go

package server
import (
"net/http"
"slices"
)
// CORSOptions configures CORS behavior for the server HTTP API.
type CORSOptions struct {
AllowOrigins []string // Allowed origins; default ["*"].
}
// WithCORS wraps an http.Handler with CORS headers.
func WithCORS(h http.Handler, opts CORSOptions) http.Handler {
origins := opts.AllowOrigins
if len(origins) == 0 {
origins = []string{"*"}
}
wildcard := len(origins) == 1 && origins[0] == "*"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
matched := false
if wildcard {
w.Header().Set("Access-Control-Allow-Origin", "*")
matched = true
} else if slices.Contains(origins, origin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Vary", "Origin")
matched = true
}
if matched {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Max-Age", "86400")
}
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
h.ServeHTTP(w, r)
})
}