Files
qitongxue-api/internal/logic/middleware.go
2026-09-17 14:42:44 +08:00

45 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package logic
import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// CORS 允许跨域(管理后台与 H5 联调)
func CORS(r *ghttp.Request) {
r.Response.CORSDefault()
if r.Method == "OPTIONS" {
r.Exit()
}
r.Middleware.Next()
}
// Response 统一响应封装:{code, message, result}
// 前端约定code=0 成功401 未登录4001 模块未授权。
func Response(r *ghttp.Request) {
r.Middleware.Next()
// 鉴权中间件等已直接写响应(如 401不再二次包装
if r.Response.BufferLength() > 0 {
return
}
var (
err = r.GetError()
res = r.GetHandlerResponse()
)
if err != nil {
code := gerror.Code(err)
codeInt := code.Code()
if code == gcode.CodeNil {
codeInt = 500
} else if code == gcode.CodeValidationFailed {
codeInt = 422
}
r.Response.WriteJson(g.Map{"code": codeInt, "message": err.Error(), "result": nil})
return
}
r.Response.WriteJson(g.Map{"code": 0, "message": "ok", "result": res})
}