Files
EasyGoAdmin_GoFrame_EleVue/internal/middleware/cors.go
T
2026-10-20 11:37:25 +08:00

30 lines
991 B
Go

package middleware
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// ============================== 跨域中间件 ==============================
// CORS 跨域处理
//
// 读取配置 cors.allowOrigin:为空或为 * 时使用框架内置默认策略;
// 配置为具体来源时显式回显,并对预检请求直接返回 204
func CORS(r *ghttp.Request) {
origin := g.Cfg().MustGet(r.Context(), "cors.allowOrigin").String()
if origin == "" || origin == "*" {
r.Response.CORSDefault()
} else {
r.Response.Header().Set("Access-Control-Allow-Origin", origin)
r.Response.Header().Set("Access-Control-Allow-Credentials", "true")
r.Response.Header().Set("Access-Control-Allow-Headers", "Origin,Authorization,Content-Type,Accept,Token,X-Requested-With")
r.Response.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
if r.Method == "OPTIONS" {
r.Response.WriteStatus(204)
return
}
}
r.Middleware.Next()
}