Golang Echo框架实现API统一返回格式

Golang的Echo框架中,上下文echo.Context是一个接口,可以通过它重写默认的Context.JSON方法来自定义返回格式

首先定义一下接口的格式

1
2
3
4
type CommonResponse struct {
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}

定义一个Context结构体,继承echo.Context

1
2
3
type Context struct {
echo.Context
}

重写JSON方法

1
2
3
4
5
6
7
func (c *Context) JSON(code int, i interface{}) error {
resp := CommonResponse{
Message: http.StatusText(code),
Data: i,
}
return c.Context.JSON(code, resp)
}

然后在中间件中注入自己的Context

1
2
3
4
5
func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return next(&Context{Context: c})
}
}

由于没有新增方法,只是重写了JSON方法,所以无需转换类型就可直接使用

1
2
3
func Hello(c echo.Context) error {
return c.JSON(http.StatusOK, "Hello")
}

Golang Echo框架实现API统一返回格式

https://jktu.cc/Golang-Echo框架实现API统一返回格式/

作者

udp_bbr

发布于

2021-12-13

更新于

2022-09-08

许可协议