This commit is contained in:
2025-08-28 17:09:21 +08:00
parent f324f15397
commit ecc7495954
6 changed files with 48 additions and 10 deletions

View File

@@ -27,7 +27,7 @@ func (m *CORSMiddleware) GetName() string {
// GetPriority 返回中间件优先级
func (m *CORSMiddleware) GetPriority() int {
return 100 // 高优先级,最先执行
return 95 // 在PanicRecovery(100)之后SecurityHeaders(85)之前执行
}
// Handle 返回中间件处理函数
@@ -39,22 +39,43 @@ func (m *CORSMiddleware) Handle() gin.HandlerFunc {
}
}
// 获取CORS配置
origins := m.getAllowedOrigins()
methods := m.getAllowedMethods()
headers := m.getAllowedHeaders()
config := cors.Config{
AllowAllOrigins: false,
AllowOrigins: m.getAllowedOrigins(),
AllowMethods: m.getAllowedMethods(),
AllowHeaders: m.getAllowedHeaders(),
AllowOrigins: origins,
AllowMethods: methods,
AllowHeaders: headers,
ExposeHeaders: []string{
"Content-Length",
"Content-Type",
"X-Request-ID",
"X-Response-Time",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Headers",
},
AllowCredentials: true,
MaxAge: 86400, // 24小时
// 增加Chrome兼容性
AllowWildcard: false,
AllowBrowserExtensions: false,
}
return cors.New(config)
// 创建CORS中间件
corsMiddleware := cors.New(config)
// 返回包装后的中间件
return func(c *gin.Context) {
// 调用实际的CORS中间件
corsMiddleware(c)
// 继续处理下一个中间件或处理器
c.Next()
}
}
// IsGlobal 是否为全局中间件