2015-11-12 15:14:49 +01:00
# CORS gin's middleware
2016-10-19 20:51:59 +08:00
[](https://travis-ci.org/gin-contrib/cors)
[](https://codecov.io/gh/gin-contrib/cors)
[](https://goreportcard.com/report/github.com/gin-contrib/cors)
[](https://godoc.org/github.com/gin-contrib/cors)
[](https://gitter.im/gin-gonic/gin?utm_source=badge& utm_medium=badge& utm_campaign=pr-badge& utm_content=badge)
2015-11-12 15:14:49 +01:00
Gin middleware/handler to enable CORS support.
## Usage
2016-10-31 16:19:39 +08:00
### Start using it
2016-11-09 14:27:26 +08:00
Download and install it:
2016-10-31 16:19:39 +08:00
```sh
$ go get gopkg.in/gin-contrib/cors.v1
```
2016-11-09 14:27:26 +08:00
Import it in your code:
2016-10-31 16:19:39 +08:00
```go
import "gopkg.in/gin-contrib/cors.v1"
```
2016-10-19 20:51:59 +08:00
### Canonical example:
2015-11-12 15:14:49 +01:00
```go
package main
import (
"time"
2016-10-31 16:19:39 +08:00
"gopkg.in/gin-contrib/cors.v1"
2016-10-31 08:52:00 +08:00
"gopkg.in/gin-gonic/gin.v1"
2015-11-12 15:14:49 +01:00
)
func main() {
router := gin.Default()
// CORS for https://foo.com and https://github.com origins, allowing:
// - PUT and PATCH methods
// - Origin header
// - Credentials share
// - Preflight requests cached for 12 hours
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()
}
```
2016-10-19 20:51:59 +08:00
### Using DefaultConfig as start point
2015-11-12 15:14:49 +01:00
```go
func main() {
2016-10-19 20:51:59 +08:00
router := gin.Default()
// - No origin allowed by default
// - GET,POST, PUT, HEAD methods
// - Credentials share disabled
// - Preflight requests cached for 12 hours
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://google.com"}
config.AddAllowOrigins("http://facebook.com")
// config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}
2015-11-12 15:14:49 +01:00
2016-10-19 20:51:59 +08:00
router.Use(cors.New(config))
router.Run()
2015-11-12 15:14:49 +01:00
}
```
2016-10-19 20:51:59 +08:00
### Default() allows all origins
2015-11-12 15:14:49 +01:00
```go
2015-11-12 15:19:58 +01:00
func main() {
2016-10-19 20:51:59 +08:00
router := gin.Default()
// same as
// config := cors.DefaultConfig()
// config.AllowAllOrigins = true
// router.Use(cors.New(config))
router.Use(cors.Default())
router.Run()
2015-11-12 15:19:58 +01:00
}
2015-11-12 15:14:49 +01:00
```