Golang gin跨域解决方案示例
目录
gin跨域解决方案cors1.gocors2.go使用中间件gin跨域解决方案
cors1.go
package middlewares import ( "github.com/gin-gonic/gin" "net/http" ) func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method origin := c.Request.Header.Get("Origin") if origin != ""{ c.Header("Access-Control-Allow-Origin", origin) //主要设置Access-Control-Allow-Origin c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type") c.Header("Access-Control-Allow-Credentials", "false") c.Set("content-type", "application/json") } if method == "OPTIONS"{ c.AbortWithStatus(http.StatusNoContent) } c.Next() } }
cors2.go
func Cors() gin.HandlerFunc { return cors.New(cors.Config{ AllowAllOrigins: false, AllowOrigins: nil, AllowOriginFunc: func(origin string) bool { return true }, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}, AllowHeaders: []string{"Authorization", "ts", "Accept", "Origin", "DNT", "X-CustomHeader", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Content-Range", "Range"}, AllowCredentials: true, MaxAge: 10 * time.Minute, }) }
使用中间件
package router import ( "github.com/gin-gonic/gin" "goproejct/controllers" "goproejct/middlewares"//引入中间件goproject是项目名 根据自己情况 ) func InitRouter() { router := gin.Default() router.Use(Cors())//使用中间件 v1 := router.Group("v1") { v1.POST("/login", controllers.Login) v1.POST("/regist", controllers.Regist) } router.Run(":8000") }
以上就是Golang gin跨域解决方案的详细内容,更多关于gin-跨域解决方案的资料请关注脚本之家其它相关文章!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?