Files

52 lines
1.4 KiB
Go
Raw Permalink Normal View History

2025-11-17 14:11:46 +08:00
package middleware
import (
"net/http"
2025-11-28 15:18:10 +08:00
"dianshang/pkg/logger"
2025-11-17 14:11:46 +08:00
"github.com/gin-gonic/gin"
)
// CORSMiddleware 跨域中间件
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
2025-11-28 15:18:10 +08:00
// 记录 CORS 请求
logger.Debugf("[CORS] Method=%s, Origin=%s, Path=%s", method, origin, c.Request.URL.Path)
2025-11-17 14:11:46 +08:00
2025-11-28 15:18:10 +08:00
// 允许所有域名跨域访问
2025-11-17 14:11:46 +08:00
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
} else {
c.Header("Access-Control-Allow-Origin", "*")
}
// 设置允许的请求头
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With, X-User-ID")
2025-11-28 15:18:10 +08:00
2025-11-17 14:11:46 +08:00
// 设置允许的请求方法
c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
2025-11-28 15:18:10 +08:00
// 设置允许携带凭证Cookie等
2025-11-17 14:11:46 +08:00
c.Header("Access-Control-Allow-Credentials", "true")
2025-11-28 15:18:10 +08:00
// 设置预检请求的缓存时间24小时
2025-11-17 14:11:46 +08:00
c.Header("Access-Control-Max-Age", "86400")
2025-11-28 15:18:10 +08:00
// 暴露的响应头(允许前端访问的自定义响应头)
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type, Authorization")
2025-11-17 14:11:46 +08:00
// 处理预检请求
if method == "OPTIONS" {
2025-11-28 15:18:10 +08:00
logger.Infof("[CORS] 预检请求 Origin=%s, Path=%s", origin, c.Request.URL.Path)
2025-11-17 14:11:46 +08:00
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
2025-11-28 15:18:10 +08:00
}