gin-golang 处理CORS跨域的函数
处理浏览器的options请求时,返回200状态即可
以下是处理函数
func CorsHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, OPTIONS")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Expose-Headers", "*")
if c.Request.Method == "OPTIONS" {
c.JSON(http.StatusOK, "")
c.Abort()
return
}
c.Next()
}
}
在router里加入即可
func InitRouter() *gin.Engine {
gin.SetMode(config.AppMode)
r := gin.New()
//cors handeler
r.Use(CorsHandler())
........
}