主要目的是对 echo 返回数据全局统一,如:
{
  "code": 200,
  "data": [],
  "msg: "ok
}
由于考虑项目后面维护不想当统一格式发生改变时每个方法都需要修改一次,目前暂时解决方案是利用中间件:
type CustomCtx struct {
  echo.Context
}
type RspFormat struct {
  ctx echo.Context `json:"-"`
  C int `json:"code"`
  D interface{} `json:"data"`
  M string `json:"msg"`
}
func (ctx CustomCtx) Rsp(status int) *RspFormat {
  return &RspFormat{
    ctx: ctx,
    C: status,
  }
}
func (rsp RspFormat) Data(i interface{}) *RspFormat {
  rsp.D = i
  return &rsp
}
func (rsp RspFormat) Msg(msg string) *RspFormat {
  rsp.M = msg
  return &rsp
}
func (rsp RspFormat) Do() errors {
  return rsp.ctx.JSON(rsp.Code, rsp)
}
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
  return func(c echo.Context) error {
    return next(CustomCtx{c})
  }
})
e.Add("GET", "/", func(c echo.Context) errors {
  return c.(CustomCtx).Rsp(200).Msg("Success").Data("data!").Do()
})
有没有更好的方式解决全局统一格式的问题?比如重写 Response.Write 这些?爬墙爬怕了……
|      1none      2022-01-08 11:49:42 +08:00 如果格式发生变化,数据传参数的地方应该都会发生变化,不可避免要改每个方法吧 |