package middleware import ( "net/http" "github.com/gin-gonic/gin" "golang.org/x/exp/slices" ) func CORSMiddleware(allowOrigin []string) gin.HandlerFunc { return func(c *gin.Context) { httpOrigin := c.Request.Header.Get("Origin") // 检测origin是否在CORS列表内 if slices.Contains(allowOrigin, httpOrigin) { c.Writer.Header().Set("Access-Control-Allow-Origin", httpOrigin) c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE") c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With, Range") } // 直接返回OPTIONS请求 if c.Request.Method == http.MethodOptions { c.AbortWithStatus(http.StatusNoContent) return } c.Request.Header.Del("Origin") c.Next() } }