This commit is contained in:
2026-07-31 17:36:25 +08:00
parent 7a1a7c2da6
commit 98bf7ed6a9
2 changed files with 27 additions and 21 deletions

View File

@@ -2,26 +2,32 @@
package middleware
import (
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
const (
allowedHeaders = "Origin, Content-Length, Content-Type, Workspace, Request-Id, Authorization, Token"
allowedMethods = "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"
)
// Cors 允许平台前端跨域调用 API包括状态更新使用的 PATCH 方法。
func Cors() gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Headers", allowedHeaders)
ctx.Header("Access-Control-Allow-Methods", allowedMethods)
if ctx.Request.Method == http.MethodOptions {
ctx.AbortWithStatus(http.StatusNoContent)
return
}
ctx.Next()
}
return cors.New(cors.Config{
AllowOriginFunc: func(origin string) bool {
return true // 允许所有域名
},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{
"Origin",
"Content-Type",
"Authorization",
"X-Requested-With",
"X-App-Id",
"X-Doip-App-Id",
"X-Lowcode-Mode",
"X-Lowcode-Org",
"Token",
},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true, // 支持 credentials
MaxAge: 12 * time.Hour,
})
}