README.md (2401B)
1 # CORS gin's middleware 2 3 [](https://github.com/gin-contrib/cors/actions/workflows/go.yml) 4 [](https://codecov.io/gh/gin-contrib/cors) 5 [](https://goreportcard.com/report/github.com/gin-contrib/cors) 6 [](https://godoc.org/github.com/gin-contrib/cors) 7 8 Gin middleware/handler to enable CORS support. 9 10 ## Usage 11 12 ### Start using it 13 14 Download and install it: 15 16 ```sh 17 go get github.com/gin-contrib/cors 18 ``` 19 20 Import it in your code: 21 22 ```go 23 import "github.com/gin-contrib/cors" 24 ``` 25 26 ### Canonical example 27 28 ```go 29 package main 30 31 import ( 32 "time" 33 34 "github.com/gin-contrib/cors" 35 "github.com/gin-gonic/gin" 36 ) 37 38 func main() { 39 router := gin.Default() 40 // CORS for https://foo.com and https://github.com origins, allowing: 41 // - PUT and PATCH methods 42 // - Origin header 43 // - Credentials share 44 // - Preflight requests cached for 12 hours 45 router.Use(cors.New(cors.Config{ 46 AllowOrigins: []string{"https://foo.com"}, 47 AllowMethods: []string{"PUT", "PATCH"}, 48 AllowHeaders: []string{"Origin"}, 49 ExposeHeaders: []string{"Content-Length"}, 50 AllowCredentials: true, 51 AllowOriginFunc: func(origin string) bool { 52 return origin == "https://github.com" 53 }, 54 MaxAge: 12 * time.Hour, 55 })) 56 router.Run() 57 } 58 ``` 59 60 ### Using DefaultConfig as start point 61 62 ```go 63 func main() { 64 router := gin.Default() 65 // - No origin allowed by default 66 // - GET,POST, PUT, HEAD methods 67 // - Credentials share disabled 68 // - Preflight requests cached for 12 hours 69 config := cors.DefaultConfig() 70 config.AllowOrigins = []string{"http://google.com"} 71 // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"} 72 // config.AllowAllOrigins = true 73 74 router.Use(cors.New(config)) 75 router.Run() 76 } 77 ``` 78 note: while Default() allows all origins, DefaultConfig() does not and you will still have to use AllowAllOrigins 79 80 ### Default() allows all origins 81 82 ```go 83 func main() { 84 router := gin.Default() 85 // same as 86 // config := cors.DefaultConfig() 87 // config.AllowAllOrigins = true 88 // router.Use(cors.New(config)) 89 router.Use(cors.Default()) 90 router.Run() 91 } 92 ```