package middlewares import ( "net/http" "github.com/gin-gonic/gin" ) // CORS 跨域中间件 func CORS() gin.HandlerFunc { return func(c *gin.Context) { origin := c.Request.Header.Get("Origin") // 设置CORS头部 c.Header("Access-Control-Allow-Origin", origin) c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS") c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") c.Header("Access-Control-Allow-Credentials", "true") c.Header("Access-Control-Max-Age", "86400") // 处理预检请求 if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) return } c.Next() } }