前言 gin開啓跨域,只須要添加一個全局中間件到路由器便可git
gin 中間件
gin的中間件能夠添加到全局, 也能夠添加到單個路由上github
添加到全局golang
r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery())
這裏的兩個中間件就是 gin.Default()幫咱們初始化的兩個中間件跨域
添加到單個路由函數
authorized := r.Group("/") authorized.Use(AuthRequired())
gin開啓跨域
gin開啓跨域其實仍是很簡單的, 演示代碼以下:ui
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() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Expose-Headers", "Access-Control-Allow-Origin") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } defer func() { if err := recover(); err != nil { core.Logger.Error("Panic info is: %v", err) core.Logger.Error("Panic info is: %s", debug.Stack()) } }() c.Next() } }