Set up project files and add .gitignore to exclude local build/runtime artifacts. Made-with: Cursor
47 lines
1.4 KiB
Go
47 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// CORS CORS中间件
|
|
func CORS() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 获取请求路径
|
|
path := c.Request.URL.Path
|
|
|
|
c.Header("Access-Control-Allow-Origin", "*")
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
|
// 添加 WebSocket 升级所需的头
|
|
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, Connection, Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version, Sec-WebSocket-Protocol, Sec-WebSocket-Extensions")
|
|
c.Header("Access-Control-Expose-Headers", "Content-Length, Connection, Upgrade")
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
|
|
// 处理 WebSocket 升级请求的预检
|
|
if c.Request.Method == "OPTIONS" {
|
|
log.Printf("[CORS] OPTIONS 预检请求: %s", path)
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
|
|
// 针对 WebSocket 路径的特殊处理
|
|
if path == "/ws" {
|
|
connection := c.GetHeader("Connection")
|
|
upgrade := c.GetHeader("Upgrade")
|
|
log.Printf("[CORS] WebSocket 请求: Connection=%s, Upgrade=%s", connection, upgrade)
|
|
|
|
// 检查是否是有效的 WebSocket 升级请求
|
|
if strings.Contains(strings.ToLower(connection), "upgrade") && strings.ToLower(upgrade) == "websocket" {
|
|
log.Printf("[CORS] 有效的 WebSocket 升级请求")
|
|
} else {
|
|
log.Printf("[CORS] 警告: 不是有效的 WebSocket 升级请求!")
|
|
}
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|