根本数据类型

syntax = "proto3";// 所有根本数据类型// protoc --go_out=. scalar.protooption 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.protooption 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.protooption 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.protooption 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字段是不平安的

参考

  • https://developers.google.com...
  • https://colobu.com/2019/10/03...