This commit is contained in:
xujiang
2025-07-10 18:09:11 +08:00
parent 5cbdc5af73
commit 604b9e59ba
95 changed files with 23709 additions and 19 deletions

View File

@ -0,0 +1,58 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"photography-backend/internal/config"
)
// CORSMiddleware CORS中间件
func CORSMiddleware(cfg *config.CORSConfig) gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
// 检查是否允许的来源
allowed := false
for _, allowedOrigin := range cfg.AllowedOrigins {
if allowedOrigin == "*" || allowedOrigin == origin {
allowed = true
break
}
}
if allowed {
c.Header("Access-Control-Allow-Origin", origin)
}
// 设置其他CORS头
c.Header("Access-Control-Allow-Methods", joinStrings(cfg.AllowedMethods, ", "))
c.Header("Access-Control-Allow-Headers", joinStrings(cfg.AllowedHeaders, ", "))
c.Header("Access-Control-Max-Age", "86400")
if cfg.AllowCredentials {
c.Header("Access-Control-Allow-Credentials", "true")
}
// 处理预检请求
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
// joinStrings 连接字符串数组
func joinStrings(strs []string, sep string) string {
if len(strs) == 0 {
return ""
}
result := strs[0]
for i := 1; i < len(strs); i++ {
result += sep + strs[i]
}
return result
}