2.1 proto文件的编写与生成

未匹配的标注

安装

上一篇文章我们已经安装过Proto但是还是不能生成gogo-micro版本的对应的文件。

所以我们还需要安装protoc-gen-goprotoc-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是定义ReqAccountRegisterResAccountRegister结构体。

account.pb.go定义了AccountService接口。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~