// // cors.go // Copyright (C) 2022 tiglog // // Distributed under terms of the MIT license. // package middleware import ( "net/http" "github.com/gin-gonic/gin" "git.hexq.cn/tiglog/golib/helper" ) func NewCors(origins []string) gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method origin := c.Request.Header.Get("Origin") if helper.InStringSlice(origin, origins) { c.Header("Access-Control-Allow-Origin", origin) c.Header("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, Authorization") c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT") c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type") c.Header("Access-Control-Allow-Credentials", "true") } // 放行所有OPTIONS方法 if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } // 处理请求 c.Next() } }