gin框架,cors中间件解决跨域问题
Go  /  管理员 发布于 4年前   1828
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())完
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
