package middleware import ( "github.com/gin-gonic/gin" "net/http" ) // Cors 跨域处理 func Cors() gin.HandlerFunc { return func(context *gin.Context) { method := context.Request.Method origin := context.Request.Header.Get("Origin") context.Header("Access-Control-Allow-Origin", origin) context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id") context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT") context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") context.Header("Access-Control-Allow-Credentials", "true") //放行所有的option方法 if method == "OPTIONS" { context.AbortWithStatus(http.StatusNoContent) } //处理请求 context.Next() } }