49 lines
1.4 KiB
Go
49 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/JACKYMYPERSON/hldrCenter/config"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func CorsMiddleware(serverConfig *config.ServerConfig) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 1. 打印配置的允许源(调试用,确认配置是否正确加载)
|
|
fmt.Printf("允许的前端源:%v\n", serverConfig.AllowedOrigins)
|
|
|
|
// 2. 获取请求的Origin头
|
|
origin := c.Request.Header.Get("Origin")
|
|
fmt.Printf("当前请求源:%s\n", origin) // 调试用
|
|
|
|
// 3. 宽松的跨域匹配逻辑
|
|
allowOrigin := ""
|
|
if len(serverConfig.AllowedOrigins) > 0 {
|
|
for _, allowed := range serverConfig.AllowedOrigins {
|
|
// 支持通配符*,或精确匹配
|
|
if allowed == "*" || allowed == origin {
|
|
allowOrigin = origin
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if allowOrigin != "" {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", allowOrigin)
|
|
}
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
|
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
c.Writer.Header().Set("Access-Control-Max-Age", "86400") // 24小时缓存预检请求
|
|
|
|
// 6. 处理OPTIONS预检请求
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(http.StatusNoContent) // 使用204更规范
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|