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
接口。
推荐文章: