Golang Echo框架实现API统一返回格式
Golang的Echo框架中,上下文echo.Context
是一个接口,可以通过它重写默认的Context.JSON
方法来自定义返回格式
首先定义一下接口的格式
1 | type CommonResponse struct { |
定义一个Context
结构体,继承echo.Context
1 | type Context struct { |
重写JSON
方法
1 | func (c *Context) JSON(code int, i interface{}) error { |
然后在中间件中注入自己的Context
1 | func(next echo.HandlerFunc) echo.HandlerFunc { |
由于没有新增方法,只是重写了JSON
方法,所以无需转换类型就可直接使用
1 | func Hello(c echo.Context) error { |
Golang Echo框架实现API统一返回格式