2.1 proto文件的编写与生成
安装#
上一篇文章我们已经安装过 Proto
但是还是不能生成 go
与 go-micro
版本的对应的文件。
所以我们还需要安装 protoc-gen-go
和 protoc-gen-micro
这 2 个插件
go get -u github.com/golang/protobuf/protoc-gen-go
go get github.com/micro/micro/v2/cmd/protoc-gen-micro@master
编写 proto 文件#
# 创建文件夹
mkdir -p goprotobuf/proto goprotobuf/build
# 创建文件
vim goprotobuf/proto/account.proto
然后我们编写如下内容:
syntax="proto3";
package proto;
option go_package=".;proto";
service AccountService{
rpc AccountRegister(ReqAccountRegister) returns(ResAccountRegister){}
}
message ReqAccountRegister{
string username=1;
string password=2;
}
message ResAccountRegister{
int32 code=1;
string message=2;
}
创建一个 request
跟一个 response
结构体。其中,request
需要传递 username
(用户名) 跟 password
(密码)。当请求成功后,收到的 response
中包含 code
(内部状态码) 跟 message
(信息)
生成#
# protoc --go_out=转换输出为go文件的目录 --micro_out=转换输出为micro微服务文件的目录 原始proto文件所在位置
protoc --go_out=goprotobuf/build --micro_out=goprotobuf/build goprotobuf/proto/account.proto
生成成功后,我们
> ls goprotobuf/build
account.pb.go account.pb.micro.go
account.pb.go
是定义 ReqAccountRegister
与 ResAccountRegister
结构体。
account.pb.go
定义了 AccountService
接口。
推荐文章: