|
|
5 years ago | |
|---|---|---|
| .. | ||
| command | 5 years ago | |
| ctx | 5 years ago | |
| execx | 5 years ago | |
| gen | 5 years ago | |
| parser | 5 years ago | |
| CHANGELOG.md | 5 years ago | |
| README.md | 5 years ago | |
Goctl Rpc是goctl脚手架下的一个rpc服务代码生成模块,支持proto模板生成和rpc服务代码生成,通过此工具生成代码你只需要关注业务逻辑编写而不用去编写一些重复性的代码。这使得我们把精力重心放在业务上,从而加快了开发效率且降低了代码出错率。
$ goctl rpc template -o=user.proto
syntax = "proto3";
package remote;
message Request {
// 用户名
string username = 1;
// 用户密码
string password = 2;
}
message Response {
// 用户名称
string name = 1;
// 用户性别
string gender = 2;
}
service User {
// 登录
rpc Login(Request)returns(Response);
}
生成user rpc服务
$ goctl rpc proto -src=user.proto
代码tree
user
├── etc
│ └── user.json
├── internal
│ ├── config
│ │ └── config.go
│ ├── handler
│ │ ├── loginhandler.go
│ │ └── userhandler.go
│ ├── logic
│ │ └── loginlogic.go
│ └── svc
│ └── servicecontext.go
├── pb
│ └── user.pb.go
├── shared
│ ├── mockusermodel.go
│ ├── types.go
│ └── usermodel.go
├── user.go
└── user.proto
在使用goctl生成rpc服务代码时,我们默认会根据开发人员正在开发的工程依赖的github.com/golang/protobuf自动将插件重新go install到${GOPATH}/bin中,
寻找方法:
对于$ go version不低于1.5版本的的工程,会优先寻找$ go env GOMODCACHE目录,如果没有则去${GOPATH}中查找(见下文),而低于1.5版本的则会优先从${GOPATH}/pkg/mod目录下查找,否则也从% GOPATH中查找(见下文)
对于没有使用go mod的工程,则默认当作在${GOPATH}中处理(暂不支持用户自定义的GOPATH),而这种情况下则会默认从${GOPATH}/src中查找
注意:
- 对于以上两种工程如果没有在对应目录查找到
protoc-gen-go则会提示相应错误,尽管protoc-gen-go可能在其他已经设置环境变量的目录中,这个将在后面版本进行优化。- 对于go mod工程,如果工程没有依赖
github.com/golang/protobuf则需要提前引入。
$ goctl rpc proto -h
NAME:
goctl rpc proto - generate rpc from proto"
USAGE:
goctl rpc proto [command options] [arguments...]
OPTIONS:
--src value, -s value the file path of the proto source file
--dir value, -d value the target path of the code,default path is "${pwd}". [option]
--service value, --srv value the name of rpc service. [option]
--shared value the dir of the shared file,default path is "${pwd}/shared. [option]"
--idea whether the command execution environment is from idea plugin. [option]
参数说明
shell script
user
├── cmd
│ └── rpc
│ └── user.proto
则服务名称亦为user,而非proto所在文件夹名称了,这里推荐使用这种结构,可以方便在同一个服务名下建立不同类型的服务(api、rpc、mq等),便于代码管理与维护。
* --shared 非必填,默认为$dir(xxx.proto)/shared,rpc client逻辑代码存放目录。
关注业务代码编写,将重复性、与业务无关的工作交给goctl,生成好rpc服务代码后,开饭人员仅需要修改
对于需要进行rpc mock的开发人员,在安装了mockgen工具的前提下可以在rpc的shared文件中生成好对应的mock文件。
shell script
// Code generated by goctl. DO NOT EDIT!
// Source: xxx.proto
的标识,请注意不要将也写业务性代码写在里面。
# 下一步规划
* 尽快支持windows端rpc生成