CORS
Cross-Origin Resource Sharing middleware for controlling access from web browsers.
Usage
r.Use(middleware.CORS(middleware.DefaultCORSConfig()))
Configuration
config := middleware.DefaultCORSConfig()
config.AllowedOrigins = []string{"https://app.example.com"}
config.AllowCredentials = true
r.Use(middleware.CORS(config))
Options
| Option | Default | Description |
|---|---|---|
AllowedOrigins | [] | Allowed origins (e.g., ["https://app.example.com"]) |
AllowedMethods | GET, POST, PUT, DELETE, PATCH, OPTIONS | Allowed HTTP methods |
AllowedHeaders | Content-Type, Authorization | Allowed request headers |
AllowCredentials | false | Allow cookies and auth headers |
ExposedHeaders | ["Content-Length", "Date"] | Response headers exposed to JS |
MaxAge | 3600 | Preflight cache duration (seconds) |
How It Works
- Handles
OPTIONSpreflight requests automatically - Sets
Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Allow-Headers, andAccess-Control-Max-Ageheaders - When
AllowCredentialsis true, mirrors the requesting origin (wildcard*is not allowed with credentials per spec)