Goctl Rpc是goctl腳手架下的一個rpc服務(wù)代碼生成模塊,支持proto模板生成和rpc服務(wù)代碼生成,通過此工具生成代碼你只需要關(guān)注業(yè)務(wù)邏輯編寫而不用去編寫一些重復(fù)性的代碼。這使得我們把精力重心放在業(yè)務(wù)上,從而加快了開發(fā)效率且降低了代碼出錯率。
通過命令 ?goctl rpc new ${servieName}
?生成
如生成greet rpc服務(wù):
goctl rpc new greet
執(zhí)行后代碼結(jié)構(gòu)如下:
.
├── etc
│ └── greet.yaml
├── go.mod
├── go.sum
├── greet
│ ├── greet.go
│ ├── greet.pb.go
│ └── greet_grpc.pb.go
├── greet.go
├── greet.proto
└── internal
├── config
│ └── config.go
├── logic
│ └── pinglogic.go
├── server
│ └── greetserver.go
└── svc
└── servicecontext.go
goctl rpc template -o=user.proto
syntax = "proto3";
package user;
option go_package="./user";
message Request {
string ping = 1;
}
message Response {
string pong = 1;
}
service User {
rpc Ping(Request) returns(Response);
}
$ goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
goctl rpc protoc -h
NAME:
goctl rpc protoc - generate grpc code
USAGE:
example: goctl rpc protoc xx.proto --go_out=./pb --go-grpc_out=./pb --zrpc_out=.
DESCRIPTION:
for details, see https://go-zero.dev/cn/goctl-rpc.html
OPTIONS:
--zrpc_out value the zrpc output directory
--style value the file naming format, see [https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/readme.md]
--home value the goctl home path of the template
--remote value the remote git repo of the template, --home and --remote cannot be set at the same time, if they are, --remote has higher priority
The git repo directory must be consistent with the https://github.com/zeromicro/go-zero-template directory structure
--branch value the branch of the remote repo, it does work with --remote
你可以理解為 zrpc 代碼生成是用 goctl rpc $protoc_command --zrpc_out=${output} 模板,如原來生成 grpc 代碼指令為
$ protoc user.proto --go_out=. --go-grpc_out=.
則生成 zrpc 代碼指令就為
$ goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
- --go_out 與 --go-grpc_out 生成的最終目錄必須一致
- --go_out & --go-grpc_out 和 --zrpc_out 的生成的最終目錄必須不為同一目錄,否則pb.go和_grpc.pb.go就與main函數(shù)同級了,這是不允許的。 --go_out 與 --go-grpc_out 生產(chǎn)的目錄會受 --go_opt 和 --grpc-go_opt 和proto源文件中 go_package值的影響。
關(guān)注業(yè)務(wù)代碼編寫,將重復(fù)性、與業(yè)務(wù)無關(guān)的工作交給goctl,生成好rpc服務(wù)代碼后,開發(fā)人員僅需要修改
// Code generated by goctl. DO NOT EDIT!
// Source: xxx.proto
對于rpc中的requestType和returnType必須在main proto文件定義,對于proto中的message可以像protoc一樣import其他proto文件。
syntax = "proto3";
package greet;
option go_package = "./greet";
import "base/common.proto";
message Request {
string ping = 1;
}
message Response {
string pong = 1;
}
service Greet {
rpc Ping(base.In) returns(base.Out);// request和return 不支持import
}
syntax = "proto3";
package greet;
option go_package = "./greet";
import "base/common.proto";
message Request {
base.In in = 1;// 支持import
}
message Response {
base.Out out = 2;// 支持import
}
service Greet {
rpc Ping(Request) returns(Response);
}
更多建議: