Files
hldrCenter/server/middleware/cors.go
2025-10-04 20:48:50 +08:00

40 lines
1000 B
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
func CorsMiddleware(cfg *config.ServerConfig) gin.HandlerFunc {
return func(c *gin.Context) {
// 处理跨域请求头
origin := c.Request.Header.Get("Origin")
if origin != "" && isAllowedOrigin(origin, cfg.AllowedOrigins) {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
// 处理预检请求
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusOK)
return
}
c.Next()
}
}
// 检查来源是否在允许的列表中
func isAllowedOrigin(origin string, allowedOrigins []string) bool {
for _, allowed := range allowedOrigins {
if allowed == "*" || allowed == origin {
return true
}
}
return false
}