环境配置
Goctl 环境配置
Goctl 介绍
goctl 是 go-zero 微服务框架下的代码生成工具。使用 goctl 可显著提升开发效率,让开发人员将时间重点放在业务开发上。
其功能有:
- api服务生成
- rpc服务生成
- model代码生成
- 模板管理
Goctl安装
1
2
3
4
5
|
# Go 1.15 及之前版本
GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/zeromicro/go-zero/tools/goctl@latest
# Go 1.16 及以后版本
GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest
|
(windows可以下载64位或者32位的发行版,然后放到$GOPATH/bin
目录下,然后将其添加到环境变量中)
- 方法2
从 go-zero代码仓库
git@github.com:zeromicro/go-zero.git
拉取一份源码,进入 tools/goctl/
目录下编译一下 goctl 文件,然后将其添加到环境变量中。
安装完成后 goctl -v
,如果输出版本信息则代表安装成功,例如:
1
2
|
$ goctl -v
goctl version 1.4.3 windows/amd64
|
如果显示没找到,请确认是否配置了环境变量
环境测试
值得注意的是在 1.4.3 版本的 Goctl直接使用go run greet.go -f etc/greet-api.yaml
会报错,因为httpx
包的 Error 函数发生了变化.
1
2
3
4
|
# greet/internal/handler
internal\handler\greethandler.go:16:10: undefined: httpx.ErrorCtx
internal\handler\greethandler.go:23:10: undefined: httpx.ErrorCtx
internal\handler\greethandler.go:25:10: undefined: httpx.OkJsonCtx
|
需要找到路径下 greethandler.go 文件然后把 httpx.ErrorCtx(r.Context(), w, err)
和 httpx.OkJsonCtx(r.Context(), w, resp)
改为 httpx.Error(w, err)
和 httpx.OkJson(w, resp)
然后打开项目目录下的 greet/internal/logic/greetlogic.go
,在写上如下代码:
1
2
3
4
5
6
|
func (l *GreetLogic) Greet(req *types.Request) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return &types.Response{
Message: "Hello go-zero",
}, nil
}
|
启动服务
1
2
|
$ cd greet
$ go run greet.go -f etc/greet-api.yaml
|
访问测试
1
|
curl -i -X GET http://localhost:8888/from/you
|
请求结果
1
2
3
4
5
6
7
|
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Traceparent: 00-86cef6c758a3f8456ec7b4ea331dea08-8340dfb14fdec0cf-00
Date: Tue, 13 Dec 2022 07:21:50 GMT
Content-Length: 27
{"message":"Hello go-zero"}
|
说明环境搭建完成
未完待续