Golang Go语言中 echo 自定义 Response
Golang Go语言中 echo 自定义 Response
主要目的是对 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 这些?爬墙爬怕了……
更多关于Golang Go语言中 echo 自定义 Response的实战教程也可以访问 https://www.itying.com/category-94-b0.html
如果格式发生变化,数据传参数的地方应该都会发生变化,不可避免要改每个方法吧
更多关于Golang Go语言中 echo 自定义 Response的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
#1 其实主要针对的是外部的字段统一,如code
、msg
这类,data
则是每个方法返回的数据不一的。。
还是为了免得每个响应数据都要写个return c.JSON(200, map[string]interface{}{"code": 200, "msg": "success", data: data})
在 Go 语言中使用 Echo 框架自定义响应是一个常见的需求,它允许你完全控制返回给客户端的数据格式和内容。以下是如何在 Echo 框架中实现自定义响应的一些步骤和示例代码:
-
安装 Echo 框架: 确保你已经安装了 Echo 框架,可以使用以下命令通过 Go Modules 安装:
go get -u github.com/labstack/echo/v4
-
创建自定义响应结构体: 定义一个结构体来表示你的响应格式,比如:
type CustomResponse struct { Status string `json:"status"` Message string `json:"message"` Data interface{} `json:"data,omitempty"` }
-
在处理器中设置自定义响应: 在你的 Echo 路由处理器中,创建并返回自定义响应:
func myHandler(c echo.Context) error { response := CustomResponse{ Status: "success", Message: "Operation completed successfully", Data: map[string]interface{}{"key": "value"}, } return c.JSON(http.StatusOK, response) }
-
注册路由: 将处理器注册到你的 Echo 应用中:
e := echo.New() e.GET("/my-endpoint", myHandler) e.Logger.Fatal(e.Start(":1323"))
通过这些步骤,你就可以在 Echo 框架中创建和返回自定义格式的响应了。这种方法使得响应的结构清晰且易于维护,同时也方便前端开发者理解和处理返回的数据。