fix
This commit is contained in:
58
backend-old/internal/api/middleware/cors.go
Normal file
58
backend-old/internal/api/middleware/cors.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user