基本数据类型
syntax = "proto3";
// 所有基本数据类型
// protoc --go_out=. scalar.proto
option go_package = "../service";
message scalar{
double filed1 = 1; //float64
float field2 = 2; //float32
int32 field3 = 3; //int32
int64 field4 = 4; //int64
uint32 field5 = 5; //uint32
uint64 field6 = 6; //uint64
sint32 field7 = 7; //int32
sint64 field8 = 8; //int64
fixed32 field9 = 9; //uint32
fixed64 field10 = 10; //uint64
sfixed32 field11 = 11; //int32
sfixed64 field12 = 12; //int64
bool field13 = 13; //bool
string field14 = 14; //string
bytes field15 = 15; //[]byte
}
生成的go代码
枚举类型
syntax = "proto3";
// protoc --go_out=. enumerations.proto
option go_package = "../service";
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
enum Corpus {
UNIVERSAL = 0;
WEB = 1;
IMAGES = 2;
LOCAL = 3;
NEWS = 4;
PRODUCTS = 5;
VIDEO = 6;
}
Corpus corpus = 4;
}
生成的go代码
其他消息类型
syntax = "proto3";
// protoc --go_out=. other_message_type.proto
option go_package = "../service";
message SearchResponse {
repeated Result results = 1;
}
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}
如果使用的类型定义在其他proto文件中,需要import导入
嵌套类型
syntax = "proto3";
// protoc --go_out=. nested.proto
option go_package = "../service";
message NestedSearchResponse {
message Result {
string url = 1;
string title = 2;
repeated string snippets = 3;
}
repeated Result results = 1;
}
更新消息类型
有时候你不得不修改正在使用的proto文件,比如为类型增加一个字段,protobuf支持这种修改而不影响已有的服务,不过你需要遵循一定的规则:
- 不要改变已有字段的字段编号
- 当你增加一个新的字段的时候,老系统序列化后的数据依然可以被你的新的格式所解析,只不过你需要处理新加字段的缺省值。 老系统也能解析你信息的值,新加字段只不过被丢弃了
- 字段也可以被移除,但是建议你Reserved这个字段,避免将来会使用这个字段
- int32, uint32, int64, uint64 和 bool类型都是兼容的
- sint32 和 sint64兼容,但是不和其它整数类型兼容
- string 和 bytes兼容,如果 bytes 是合法的UTF-8 bytes的话
- 嵌入类型和bytes兼容,如果bytes包含一个消息的编码版本的话
- fixed32和sfixed32, fixed64和sfixed64
- enum和int32, uint32, int64, uint64格式兼容
- 把单一一个值改变成一个新的oneof类型的一个成员是安全和二进制兼容的。把一组字段变成一个新的oneof字段也是安全的,如果你确保这一组字段最多只会设置一个。把一个字段移动到一个已存在的oneof字段是不安全的
常见问题
1.protoc-gen-go: unable to determine Go import path for xxx
在新版中,必须指定 go_package
// 通过分号分割
// 前半部分是path 表示生成文件的存放目录
// 后半部分是生成go文件的包名
option go_package="example.com/protos/foo;package_name";
具体参考这里 https://github.com/golang/pro...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。