Documentation
¶
Overview ¶
Package cors provides a configurable Cross-Origin Resource Sharing (CORS) middleware for standard net/http servers.
Correct CORS handling is subtle. This implementation:
- Matches origins against an explicit allowlist (never reflects arbitrary origins)
- Handles preflight OPTIONS requests and caches them via Access-Control-Max-Age
- Sets Vary: Origin so CDNs and proxies cache responses correctly per origin
- Rejects credentialed requests when AllowedOrigins contains a wildcard
Quick start — development (allow everything):
mux.Handle("/", cors.AllowAll()(handler))
Production:
mux.Handle("/", cors.New(cors.Config{
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
MaxAge: 12 * time.Hour,
})(handler))
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// AllowedOrigins is the list of origins that are permitted to make
// cross-origin requests. Use "*" to allow any origin (development only).
// Each entry must be an exact origin string (scheme + host + optional port),
// e.g. "https://app.example.com".
AllowedOrigins []string
// AllowedMethods lists the HTTP methods allowed for cross-origin requests.
// Defaults to ["GET", "HEAD", "POST"] when empty.
AllowedMethods []string
// AllowedHeaders lists the request headers that may be used by a
// cross-origin request. "Origin", "Accept", and "Content-Type" are always
// included per the spec.
AllowedHeaders []string
// ExposedHeaders lists response headers that browsers are allowed to
// read from the response. Simple headers are always exposed by browsers.
ExposedHeaders []string
// AllowCredentials indicates whether the request can include cookies,
// HTTP authentication, or TLS client certificates.
// Must not be combined with AllowedOrigins containing "*".
AllowCredentials bool
// MaxAge controls the Access-Control-Max-Age header sent on preflight
// responses. Limits how long browsers cache the preflight result.
// Defaults to 5 minutes.
MaxAge time.Duration
}
Config controls CORS policy.
Click to show internal directories.
Click to hide internal directories.