Files

31 lines
981 B
Go
Raw Permalink 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 common
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"
)
// UnifiedResponse 统一响应中间件:挂在客户端路由组上,输出 {"code":0,"message":"ok","data":...}。
// handler 返回 error 时输出 {code, message, data:null}code 取 gerror 附带的业务码);
// 已直接写响应体的例外场景(SSE、文件导出等)跳过包装。
func UnifiedResponse(r *ghttp.Request) {
r.Middleware.Next()
// handler 已直接写响应体(例外场景),不再包装
if r.Response.BufferLength() > 0 {
return
}
if err := r.GetError(); err != nil {
code := gerror.Code(err)
if code == gcode.CodeNil {
code = gcode.CodeInternalError
}
r.Response.WriteJson(g.Map{"code": code.Code(), "message": err.Error(), "data": nil})
return
}
r.Response.WriteJson(g.Map{"code": 0, "message": "ok", "data": r.GetHandlerResponse()})
}