Cors
Official CORS gin's middleware
Install / Use
/learn @gin-contrib/CorsREADME
gin-contrib/cors
Overview
CORS (Cross-Origin Resource Sharing) middleware for Gin.
- Enables flexible CORS handling for your Gin-based APIs.
- Highly configurable: origins, methods, headers, credentials, and more.
Installation
go get github.com/gin-contrib/cors
Import in your Go code:
import "github.com/gin-contrib/cors"
Quick Start
Allow all origins (default):
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.Default()) // All origins allowed by default
router.Run()
}
⚠️ Warning: Allowing all origins disables cookies for clients. For credentialed requests, do not allow all origins.
Advanced Usage
Custom Configuration
Configure allowed origins, methods, headers, and more:
import (
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"https://foo.com"},
AllowMethods: []string{"PUT", "PATCH"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return origin == "https://github.com"
},
MaxAge: 12 * time.Hour,
}))
router.Run()
}
DefaultConfig Reference
Start with library defaults and customize as needed:
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://google.com"}
// config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
// config.AllowAllOrigins = true
router.Use(cors.New(config))
router.Run()
}
Note:
Default()allows all origins, butDefaultConfig()does not. To allow all origins, setAllowAllOrigins = true.
Default() Convenience
Enable all origins with a single call:
router.Use(cors.Default()) // Equivalent to AllowAllOrigins = true
Configuration Reference
The middleware is controlled via the cors.Config struct. All fields are optional unless otherwise stated.
| Field | Type | Default | Description |
|-------------------------------|-----------------------------|-----------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| AllowAllOrigins | bool | false | If true, allows all origins. Credentials cannot be used. |
| AllowOrigins | []string | [] | List of allowed origins. Supports exact match, *, and wildcards. |
| AllowOriginFunc | func(string) bool | nil | Custom function to validate origin. If set, AllowOrigins is ignored. |
| AllowOriginWithContextFunc | func(*gin.Context,string)bool | nil | Like AllowOriginFunc, but with request context. |
| AllowMethods | []string | []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"} | Allowed HTTP methods. |
| AllowPrivateNetwork | bool | false | Adds Private Network Access CORS header. |
| AllowHeaders | []string | [] | List of non-simple headers permitted in requests. |
| AllowCredentials | bool | false | Allow cookies, HTTP auth, or client certs. Only if precise origins are used. |
| ExposeHeaders | []string | [] | Headers exposed to the browser. |
| MaxAge | time.Duration | 12 * time.Hour | Cache time for preflight requests. |
| AllowWildcard | bool | false | Enables wildcards in origins (e.g. https://*.example.com). |
| AllowBrowserExtensions | bool | false | Allow browser extension schemes as origins (e.g. chrome-extension://). |
| CustomSchemas | []string | nil | Additional allowed URI schemes (e.g. tauri://). |
| AllowWebSockets | bool | false | Allow ws:// and wss:// schemas. |
| AllowFiles | bool | false | Allow file:// origins (dangerous; use only if necessary). |
| OptionsResponseStatusCode | int | 204 | Custom status code for OPTIONS responses. |
Notes on Configuration
- Only one of
AllowAllOrigins,AllowOrigins,AllowOriginFunc, orAllowOriginWithContextFuncshould be set. - If
AllowAllOriginsis true, other origin settings are ignored and credentialed requests are not allowed. - If
AllowWildcardis enabled, only one*is allowed per origin string. - Use
AllowBrowserExtensions,AllowWebSockets, orAllowFilesto permit non-HTTP(s) protocols as origins. - Custom schemas allow, for example, usage in desktop apps via custom URI schemes (
tauri://, etc.). - If both
AllowOriginFuncandAllowOriginWithContextFuncare set, the context-specific function is preferred.
Examples
Advanced Options
config := cors.Config{
AllowOrigins: []string{"https://*.foo.com", "https://bar.com"},
AllowWildcard: true,
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
AllowBrowserExtensions: true,
AllowWebSockets: true,
AllowFiles: false,
CustomSchemas: []string{"tauri://"},
MaxAge: 24 * time.Hour,
ExposeHeaders: []string{"X-Custom-Header"},
AllowPrivateNetwork: true,
}
Custom Origin Validation
config := cors.Config{
AllowOriginFunc: func(origin string) bool {
// Allow any github.com subdomain or a custom rule
return strings.HasSuffix(origin, "github.com")
},
}
With Gin Context
config := cors.Config{
AllowOriginWithContextFunc: func(c *gin.Context, origin string) bool {
// Allow only if a certain header is present
return c.Request.Header.Get("X-Allow-CORS") == "yes"
},
}
Helper Methods
Dynamically add methods or headers to the config:
config.AddAllowMethods("DELETE", "OPTIONS")
config.AddAllowHeaders("X-My-Header")
config.AddExposeHeaders("X-Other-Header")
Validation & Error Handling
- Calling
Validate()on aConfigchecks for misconfiguration (called internally). - If
AllowAllOriginsis set, you cannot also setAllowOriginsor anyAllowOriginFunc. - If neither
AllowAllOrigins,AllowOriginFunc, norAllowOriginsis set, an error is raised. - If an
Related Skills
node-connect
339.3kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.9kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
339.3kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.9kCommit, push, and open a PR
