CORS
Added: v1.0.0
Cross-Origin Resource Sharing middleware for controlling access from web browsers.
Usage
go
r.Use(middleware.CORS(middleware.DefaultCORSConfig()))With Config
go
r.Use(middleware.CORS(middleware.CORSConfig{
AllowedOrigins: []string{"https://app.example.com"},
AllowCredentials: true,
}))Or start from defaults and modify:
go
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, HEAD, OPTIONS | Allowed HTTP methods |
AllowedHeaders | Content-Type, Authorization, Accept, X-Requested-With | Allowed request headers |
AllowCredentials | false | Allow cookies and auth headers |
ExposeHeaders | ["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)