1. Protobuf⇢Go转换
这里使用一个测试文件对照说明常用结构的protobuf到golang的转换。只说明关键部分代码,详细内容请查看完整文件。示例文件在目录下。
在proto文件中使用package
关键字声明包名,默认转换成go中的包名与此一致,如果需要指定不一样的包名,可以使用go_package
选项:
示例proto:
// Test 测试
message Test {
int32 age = 1;
int64 count = 2;
double money = 3;
float score = 4;
string name = 5;
bool fat = 6;
bytes char = 7;
// Status 枚举状态
FAIL = 1;
}
Status status = 8;
// Child 子结构
message Child {
string sex = 1;
}
Child child = 9;
map<string, string> dict = 10;
}
转换结果:
func (m *Test) GetAge() int32 {
if m != nil {
return m.Age
}
}
枚举类型会生成对应名称的常量,同时会有两个map方便使用:
定义一个简单的Service,有一个方法Test
,接收一个Request
参数,返回Response
:
// TestService 测试服务
service TestService {
// Test 测试方法
rpc Test(Request) returns (Response) {};
}
// Request 请求结构
message Request {
string name = 1;
}
// Response 响应结构
message Response {
生成的go代码中包含该Service定义的接口,客户端接口已经自动实现了,直接供客户端使用者调用,服务端接口需要由服务提供方实现。