gin框架,cors中间件解决跨域问题
Gin官方提供了cors跨域解决方案:
https://github.com/gin-contrib/cors
步骤:
//下载
go get github.com/gin-contrib/cors
//导入
import "github.com/gin-contrib/cors"
使用方式:
1.
package main
import (
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
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()
}
允许所有源的话直接使用
func main() {
router := gin.Default()
router.Use(cors.Default())
router.Run()
}
2.编写一个中间件函数
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
// 这里可以用*,也可以用你指定的域名
c.Header("Access-Control-Allow-Origin", "*")
// 允许头部参数
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
// 允许的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
method := c.Request.Method
//放行OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
}
// 处理请求
c.Next()
}
}
然后在路由中加入:
g.Use(Cors())
完
相关文章