Skip to content

Commit

Permalink
🐛 Fix a bug when cors set mutil host
Browse files Browse the repository at this point in the history
when cors set more than one, Failed to load resource: Access-Control-Allow-Origin cannot contain more than one origin.
  • Loading branch information
soxft committed Sep 2, 2024
1 parent a26df5b commit 922203d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 17 deletions.
18 changes: 17 additions & 1 deletion app/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,27 @@ import (
"github.com/gin-gonic/gin"
"github.com/soxft/busuanzi/config"
"github.com/spf13/viper"
"strings"
)

func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", viper.GetString("Web.Cors"))
cors := viper.GetString("Web.Cors")

// 多 cors 匹配 Failed to load resource: Access-Control-Allow-Origin cannot contain more than one origin.
if strings.Contains(cors, ",") {
for _, v := range strings.Split(cors, ",") {
allow := strings.ToLower(strings.TrimSpace(v))

if c.Request.Header.Get("Origin") == allow {
c.Header("Access-Control-Allow-Origin", allow)
break
}
}
} else {
c.Header("Access-Control-Allow-Origin", viper.GetString("Web.Cors"))
}

c.Header("Server", "busuanzi-by-xcsoft/"+config.VERSION)
if c.Request.Method == "OPTIONS" {
c.Header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS")
Expand Down
2 changes: 1 addition & 1 deletion config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Web:
Address: 0.0.0.0:8080 # 监听地址
Cors: "*" # 跨域访问
Cors: "https://xsot.cn,https://google.com" # 跨域访问
Debug: false # 是否开启debug模式
Log: true # 是否开启日志
Redis:
Expand Down
28 changes: 13 additions & 15 deletions process/webutil/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,21 @@ import (
)

func initRoute(r *gin.Engine) {
api := r.Group("/api")
{
api := r.Group("/api")
{
api.Use(middleware.Identity())
api.POST("", controller.ApiHandler)
api.GET("", controller.GetHandler)
api.PUT("", controller.PutHandler)
}
api.Use(middleware.Identity())
api.POST("", controller.ApiHandler)
api.GET("", controller.GetHandler)
api.PUT("", controller.PutHandler)
}

r.GET("/ping", controller.PingHandler)
r.GET("/ping", controller.PingHandler)

static := r.Group("/")
{
static.Use(middleware.Cache())
static.GET("/", controller.Index)
static.StaticFile("/js", config.DistPath+"/busuanzi.js")
}
r.NoRoute(middleware.Cache(), controller.Index)
static := r.Group("/")
{
static.Use(middleware.Cache())
static.GET("/", controller.Index)
static.StaticFile("/js", config.DistPath+"/busuanzi.js")
}
r.NoRoute(middleware.Cache(), controller.Index)
}

0 comments on commit 922203d

Please sign in to comment.