Files
2025-11-28 15:18:10 +08:00

52 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"dianshang/pkg/logger"
"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")
// 记录 CORS 请求
logger.Debugf("[CORS] Method=%s, Origin=%s, Path=%s", method, origin, c.Request.URL.Path)
// 允许所有域名跨域访问
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")
// 设置允许的请求方法
c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
// 设置允许携带凭证Cookie等
c.Header("Access-Control-Allow-Credentials", "true")
// 设置预检请求的缓存时间24小时
c.Header("Access-Control-Max-Age", "86400")
// 暴露的响应头(允许前端访问的自定义响应头)
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type, Authorization")
// 处理预检请求
if method == "OPTIONS" {
logger.Infof("[CORS] 预检请求 Origin=%s, Path=%s", origin, c.Request.URL.Path)
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}