45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
|
|
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})
|
|||
|
|
}
|