echo 自定义 Response

2022-01-07 21:10:05 +08:00
 SP00F

主要目的是对 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 这些?爬墙爬怕了……

1175 次点击
所在节点    Go 编程语言
2 条回复
none
2022-01-08 11:49:42 +08:00
如果格式发生变化,数据传参数的地方应该都会发生变化,不可避免要改每个方法吧
SP00F
2022-01-08 22:09:28 +08:00
@none #1 其实主要针对的是外部的字段统一,如`code`、`msg`这类,`data`则是每个方法返回的数据不一的。。
还是为了免得每个响应数据都要写个

```return c.JSON(200, map[string]interface{}{"code": 200, "msg": "success", data: data})```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/826916

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX