daShangDao_psiServer/middleware/cors.go
2026-06-15 13:47:39 +08:00

25 lines
1.1 KiB
Go

package middleware
import (
"github.com/gin-gonic/gin"
)
// Cors 跨域中间件
func Cors() gin.HandlerFunc {
// 处理CORS请求
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有源
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") // 允许携带cookie
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") // 允许的请求头
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH") // 允许的请求方法
// 处理OPTIONS请求
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204) // 返回204
return
}
// 处理正常请求
c.Next()
}
}