CORS
Regius includes a CORS (Cross-Origin Resource Sharing) middleware with flexible configuration.
Features
- Opt-out by default: CORS is enabled automatically with sensible defaults
- Configurable origins: Allow specific domains or use wildcards
- Configurable methods and headers: Control which HTTP methods and headers are permitted
- Preflight support: Automatic handling of OPTIONS requests
- Credentials support: Allow cookies and authorization headers in cross-origin requests
- Flexible application: Apply globally or to specific route groups
Usage
CORS is applied globally by default when CORS_ENABLED=true (or unset). No additional code is required.
To apply CORS only to API routes, disable global CORS in .env:
CORS_ENABLED=false
Then manually apply it in your routes file:
r.Group(func(mux chi.Router) {
mux.Use(a.CORS(regius.CORSConfig{
Enabled: true,
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowCredentials: true,
}))
// API routes here
})
Configuration Options
config := regius.CORSConfig{
Enabled: true,
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{},
MaxAge: 300,
AllowCredentials: true,
OptionsPassthrough: false,
Debug: false,
}
| Option | Type | Description |
|---|---|---|
Enabled | bool | Enable/disable CORS |
AllowedOrigins | []string | Allowed origins (use "*" for any) |
AllowedMethods | []string | Allowed HTTP methods |
AllowedHeaders | []string | Allowed request headers |
ExposedHeaders | []string | Headers exposed to the client |
MaxAge | int | Preflight cache duration in seconds |
AllowCredentials | bool | Allow cookies/auth headers |
OptionsPassthrough | bool | Let OPTIONS requests pass through |
Debug | bool | Enable debug logging |
Environment Variables
CORS_ENABLED=true
CORS_ALLOWED_ORIGINS="*"
CORS_ALLOWED_METHODS="GET,POST,PUT,DELETE,OPTIONS,PATCH,HEAD"
CORS_ALLOWED_HEADERS="Accept,Authorization,Content-Type,X-CSRF-Token"
CORS_EXPOSED_HEADERS=""
CORS_ALLOW_CREDENTIALS=true
CORS_MAX_AGE=300