go-zero使用自定义模板实现统一格式的 body 响应
·
前提
go环境的配置、goctl的安装、go-zero的基本使用默认都会
需求
go-zero框架中,默认使用goctl命令生成的代码并没有统一响应格式,现在使用自定义模板的方式实现统一响应格式:
{
"code": 0,
"msg": "OK",
"data": {}
}
步骤
1、下载模板
goctl template init
下载完成后会有提示edit on your risk,默认下载路径会在C盘


2、移动模板
将下载好的模板文件拷贝到项目目录中,以便后续操作,移动后的项目结构如下:

3、创建统一响应结构体
创建utils包、再创建统一响应结构体reponse.go

package utils
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
)
type Body struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}
func Response(w http.ResponseWriter, resp interface{}, err error) {
var body Body
if err != nil {
body.Code = -1
body.Msg = err.Error()
} else {
body.Msg = "OK"
body.Data = resp
}
httpx.OkJson(w, body)
}
4、修改handler模板
将刚刚通过goctl template下载的模板中的handler.tpl替换成如下内容:

package {{.PkgName}}
import (
"net/http"
"gozero_gorm/utils"
"github.com/zeromicro/go-zero/rest/httpx"
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
{{if .HasRequest}}var req types.{{.RequestType}}
if err := httpx.Parse(r, &req); err != nil {
httpx.Error(w, err)
return
}{{end}}
l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
{{if .HasResp}}utils.Response(w, resp, err){{else}}response.Response(w, nil, err){{end}} // 换成自己的结构体路径
}
}
如果你定义的统一相应结构体在其他路径下,只需修改最后一行代码即可
{{if .HasResp}}utils.Response(w, resp, err){{else}}response.Response(w, nil, err){{end}} // 换成自己的结构体路径
5、生成代码
goctl api go --api .\index.api --dir . --home ..\template\
相比普通的api生成该命令指定了使用的模板,也就是--home ..\template\这一项,由于模板中的handler.tpl已经被修改,所以生成后的代码会返回统一的响应格式
测试

可以看到响应结果已经成功格式化
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)