From b0d357b9bcf9891f21e74c03f45701f39aa468ed Mon Sep 17 00:00:00 2001 From: soxft Date: Wed, 18 Sep 2024 21:10:49 +0800 Subject: [PATCH] :bug: Wrong OPTION http status code when cors not match --- app/middleware/cors.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/app/middleware/cors.go b/app/middleware/cors.go index 90cf7cb..c0c492d 100644 --- a/app/middleware/cors.go +++ b/app/middleware/cors.go @@ -4,6 +4,7 @@ import ( "github.com/gin-gonic/gin" "github.com/soxft/busuanzi/config" "github.com/spf13/viper" + "net/http" "strings" ) @@ -12,25 +13,38 @@ func Cors() gin.HandlerFunc { cors := viper.GetString("Web.Cors") // 多 cors 匹配 Failed to load resource: Access-Control-Allow-Origin cannot contain more than one origin. + var corsPass = false + var origin = c.Request.Header.Get("Origin") + if strings.Contains(cors, ",") { + // 多 Cors 匹配, 判断请求多域名是否在 cors 列表中 for _, v := range strings.Split(cors, ",") { allow := strings.ToLower(strings.TrimSpace(v)) - if c.Request.Header.Get("Origin") == allow { + if origin == allow { + corsPass = true c.Header("Access-Control-Allow-Origin", allow) break } } } else { - c.Header("Access-Control-Allow-Origin", viper.GetString("Web.Cors")) + // 单 cors 匹配 // * 或者单域名 + if cors == "*" || origin == cors { + corsPass = true + } + c.Header("Access-Control-Allow-Origin", origin) } c.Header("Server", "busuanzi-by-xcsoft/"+config.VERSION) - if c.Request.Method == "OPTIONS" { + if c.Request.Method == http.MethodOptions { c.Header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS") c.Header("Access-Control-Allow-Headers", "x-bsz-referer, Authorization") c.Header("Access-Control-Max-Age", "86400") - c.AbortWithStatus(204) + if corsPass { + c.AbortWithStatus(204) + } else { + c.AbortWithStatus(403) + } return } }