一征候、Protobuf安裝
下載地址:Protocol Buffers
比如味咳,我們下載3.14.0,下載地址為:
https://github.com/protocolbuffers/protobuf/releases?expanded=true&page=4&q=v3.14.0
根據我們的電腦系統(tǒng)下載對應的二進制包陷舅,一般解壓到GOPATH/bin目錄下。
這里有個地方要注意审洞,下載的文件中有個README文件
Protocol Buffers - Google's data interchange format
Copyright 2008 Google Inc.
https://developers.google.com/protocol-buffers/
This package contains a precompiled binary version of the protocol buffer
compiler (protoc). This binary is intended for users who want to use Protocol
Buffers in languages other than C++ but do not want to compile protoc
themselves. To install, simply place this binary somewhere in your PATH.
If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.
Please refer to our official github site for more installation instructions:
https://github.com/protocolbuffers/protobuf
提示我們莱睁,如果需要使用include目錄中的內容,則我們需要把include目錄也一同拷貝到和bin目錄并列的位置芒澜,比如:
如上圖是我本地的一個位置放置關系仰剿,默認的include目錄中有一個google的目錄,這樣copy過來后痴晦,如果我們需要在proto文件中import google目錄中的文件就可以直接寫相對路徑了酥馍,比如:
這里顯示的是紅色的,不影響編譯阅酪,這是goland ide的問題旨袒,只要我們設置下ide就可以了。這里指定的位置就是我們上面安裝的時候include放置的位置术辐。設置成功后再看回到proto文件就是正常的了
編譯生成go的pb文件需要插件砚尽,安裝:
go get github.com/golang/protobuf/protoc-gen-go
如果我們用到了go-micro微服務框架,還需要安裝
go get github.com/micro/micro/v2/cmd/protoc-gen-micro
二辉词、Protobuf語法解析
標量類型 (Scalar Value Types)
proto類型 Go類型 備注
double float64
float float
int32 int32 編碼負數值相對低效
int64 int64 編碼負數值相對低效
uint32 uint32
uint64 uint64
sint32 int32 當值為負數時候必孤,編碼比int32更高效
sint64 int64 當值為負數時候,編碼比int64更高效
fixed32 uint32 當值總是大于2^28時瑞躺,編碼比uint32更高效
fixed64 uint64 當值總是大于2^56時敷搪,編碼比uint32更高效
sfixed32 int32
sfixed64 int64
bool bool
string string 只能是utf-8編碼或者7-bit ASCII文本,且長度不得大于2^32
bytes []byte 不大于2^32的任意長度字節(jié)序列
message消息
// 普通的message
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
// 枚舉 enum
enum Status {
STATUS_UNSPECIFIED = 0;
STATUS_OK = 1;
STATUS_FAIL= 2;
STATUS_UNKNOWN = -1; // 不推薦有負數
}
// 保留字段
message ReservedMessage {
reserved 2, 15, 9 to 11;
reserved "foo", "bar";
// string abc = 2; // 編譯報錯
// string foo = 3; // 編譯報錯
}
// 保留枚舉
enum ReservedEnum {
reserved 2, 15, 9 to 11, 40 to max;
reserved "FOO", "BAR";
// FOO = 0; // 編譯報錯
F = 0;
}
// nested 嵌套message
message SearchResponse {
message Result {
string url = 1 ;
string title = 2;
}
enum Status {
UNSPECIFIED = 0;
OK = 1;
FAIL= 2;
}
Result results = 1;
Status status = 2;
}
// repeated
message RepeatedMessage {
repeated SearchRequest requests = 1;
repeated Status status = 2;
repeated int32 number = 3;
}
// map類型
message MapMessage{
map<string, string> message = 1;
map<string, SearchRequest> request = 2;
}
// any 類型
import "google/protobuf/any.proto";
message AnyMessage {
string message = 1;
google.protobuf.Any details = 2;
}