![](https://images.cnblogs.com/cnblogs_com/xuange306/1699852/o_200414134249img1.jpg)
## 前言
gin开启跨域,只需要添加一个全局中间件到路由器即可
## gin 中间件
gin的中间件可以添加到全局, 也可以添加到单个路由上
**添加到全局**
```golang
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
```
> 这里的两个中间件就是 gin.Default()帮我们初始化的两个中间件
**添加到单个路由**
```golang
authorized := r.Group("/")
{
authorized.Use(AuthRequired())
}
```
## gin开启跨域代码案例
gin开启跨域其实还是很简单的, 演示代码如下:
```golang
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(Cors()) // 主要是这里
r.GET("/test", function(){
c.String(200, "success")
})
_ = r.Run(":8080")
}
// 开启跨域中间件函数
func Cors(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
// 允许的请求头, 如果有自定义的Header都要添加到这里,不然浏览器会报跨域错误
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Token, Timestamp. AppId")
// 允许的请求方式都需要添加
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
defer func() {
if err := recover(); err != nil {
public.LOGGER.Error("Panic info is: %v", err)
public.LOGGER.Error("Panic info is: %s", debug.Stack())
}
}()
c.Next()
}
```
找了下我的代码
```go
type CORS struct {
Enabled bool
AllowedHeaders []string
AllowedMethods []string
ExposeHeaders []string
MaxAge string
Origins []string
originValidator func(c *CORS, r *http.Request) (string, error)
AllowCredentials bool
}
func New() *CORS {
return &CORS{
AllowedMethods: []string{"POST", "GET", "OPTIONS"},
}
}
func (c *CORS) Preflight(w http.ResponseWriter, r *http.Request) {
if c.Enabled {
v := c.originValidator
if v == nil {
v = DefaultOriginValidator
}
origin, err := v(c, r)
if err != nil {
panic(err)
}
if origin != "" {
w.Header().Set(HeaderAccessControlAllowOrigin, origin)
w.Header().Set(HeaderVary, "Origin")
if c.MaxAge != "" {
w.Header().Set(HeaderMaxAge, c.MaxAge)
} else {
w.Header().Set(HeaderMaxAge, DefaultMaxAge)
}
if len(c.AllowedHeaders) > 0 {
w.Header().Set(HeaderAccessControlAllowHeaders, strings.Join(c.AllowedHeaders, ", "))
}
if len(c.AllowedMethods) > 0 {
w.Header().Set(HeaderAccessControlAllowMethods, strings.Join(c.AllowedMethods, ", "))
}
if len(c.ExposeHeaders) > 0 {
w.Header().Set(HeaderAccessControlExposeHeaders, strings.Join(c.ExposeHeaders, ", "))
}
if c.AllowCredentials {
w.Header().Set(HeaderAccessControlAllowCredentials, "true")
}
}
}
w.WriteHeader(200)
}
func (c *CORS) ServeMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if c.Enabled {
v := c.originValidator
if v == nil {
v = DefaultOriginValidator
}
origin, err := v(c, r)
if err != nil {
panic(err)
}
if origin != "" {
w.Header().Set(HeaderAccessControlAllowOrigin, origin)
w.Header().Set(HeaderVary, "Origin")
}
}
next(w, r)
}
```
#4
更多评论