This commit is contained in:
sjk
2025-11-28 15:18:10 +08:00
parent ad4a600af9
commit 5683f35942
188 changed files with 53680 additions and 1062 deletions

View File

@@ -3,6 +3,8 @@ package middleware
import (
"net/http"
"dianshang/pkg/logger"
"github.com/gin-gonic/gin"
)
@@ -11,8 +13,11 @@ 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 {
@@ -21,22 +26,26 @@ func CORSMiddleware() gin.HandlerFunc {
// 设置允许的请求头
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()
}
}
}