GoTest/internal/middleware/cors.go
2025-11-29 03:27:19 +08:00

32 lines
816 B
Go

package middleware
import (
"yinli-api/pkg/config"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// CORSMiddleware CORS中间件
func CORSMiddleware() gin.HandlerFunc {
cfg := config.AppConfig
if cfg == nil {
// 默认配置
return cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
})
}
return cors.New(cors.Config{
AllowOrigins: cfg.CORS.AllowOrigins,
AllowMethods: cfg.CORS.AllowMethods,
AllowHeaders: cfg.CORS.AllowHeaders,
ExposeHeaders: []string{"Content-Length", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset"},
AllowCredentials: true,
})
}