Skip to content

Commit

Permalink
🐛 Wrong OPTION http status code when cors not match
Browse files Browse the repository at this point in the history
  • Loading branch information
soxft committed Sep 18, 2024
1 parent 828da41 commit b0d357b
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions app/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/soxft/busuanzi/config"
"github.com/spf13/viper"
"net/http"
"strings"
)

Expand All @@ -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
}
}
Expand Down

0 comments on commit b0d357b

Please sign in to comment.