参考链接
https://go-zero.dev/cn/docs/advance/template
https://go-zero.dev/cn/docs/advance/error-handle
步骤一
- 创建common目录添加baseerror.go错误处理函数
1 | package errorx |
- 添加response.go
1 | //utils/response/response.go代码 |
- 此时目录结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15//baseerror.go和response.go的路径
api
├─ common
│ ├─ baseerror.go
│ └─ response.go
├─ etc
│ └─ admin-api.yaml
├─ internal
│ ├─ config
│ ├─ handle
│ ├─ logic
│ ├─ middware
│ ├─ svc
│ └─ types
└─ admin.go
步骤二
- 使用goctl生成模板,对模板修改
goctl template init
生成模板目录:
Linux&MAC:
~/.goctl/版本号/
- 修改
~/.goctl/版本号/api/handler.tpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22package {{.PkgName}}
import (
"net/http"
"更改此处为你的包名/api/common/response"
{{.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.ErrorCtx(r.Context(), w, err)
return
}
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
{{if .HasResp}}response.Response(w, resp, err){{else}}response.Response(w, nil, err){{end}}
}
}
其实就是删除官方代码
1 | if err != nil { |
更改为:
1 | {{if .HasResp}}response.Response(w, resp, err){{else}}response.Response(w, nil, err){{end}} |
4.使用
1 | goctl api go -api admin.api -dir |