Golang?gin跨域解決方案示例
更新時間:2022年04月15日 12:35:17 作者:Jeff的技術棧
這篇文章主要為大家介紹了Golang?gin跨域解決方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪
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"http://引入中間件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-跨域解決方案的資料請關注腳本之家其它相關文章!
相關文章
Go語言基礎知識總結(語法、變量、數值類型、表達式、控制結構等)
這篇文章主要介紹了Go語言基礎知識總結(語法、變量、數值類型、表達式、控制結構等),本文匯總了Go語言的入門知識,需要的朋友可以參考下2014-10-10