V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
SP00F
V2EX  ›  Go 编程语言

echo 自定义 Response

  •  
  •   SP00F · 2022-01-07 21:10:05 +08:00 · 1164 次点击
    这是一个创建于 855 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    2 条回复    2022-01-08 22:09:28 +08:00
    none
        1
    none  
       2022-01-08 11:49:42 +08:00
    如果格式发生变化,数据传参数的地方应该都会发生变化,不可避免要改每个方法吧
    SP00F
        2
    SP00F  
    OP
       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})```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2962 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:37 · PVG 22:37 · LAX 07:37 · JFK 10:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.