天天看點

windows下golang使用protobuf

windows 下安裝protoc與protoc-gen-go

Protobuf(Protocol Buffer)是google 的一種資料交換的格式,它獨立于語言,獨立于平台。google 提供了多種語言的實作:java、c#、c++、go 和 python,每一種實作都包含了相應語言的編譯器以及庫檔案。由于它是一種二進制的格式,比使用 xml 進行資料交換快許多。(也就是說,當伺服器端使用go實作,注冊了api;那麼用戶端是python實作,通過Protobuf也可以實作遠端通路)

1、protoc是Protobuf編譯器,可以從github上直接下載下傳源碼,下載下傳位址https://github.com/protocolbuffers/protobuf/releases

windows下golang使用protobuf

将下載下傳下來的protobuf放到到 $GOPATH\src\golang.org\x\protobuf 中

2、 protoc-gen-go是go版本的 Protobuf 編譯器插件,能通路網絡的情況下,隻需要運作 

go get -u github.com/golang/protobuf/protoc-gen-go 

protoc-gen-go 将自動安裝到 $GOPATH/bin 目錄下,也需要将這個目錄加入到環境變量中。

windows下golang使用protobuf

protobuf的使用方法

1、基本用法

protoc --version #檢視protoc的版本

2、代碼轉換顯例

切換到要使用的proto檔案路徑下,并打開cmd視窗執行以下指令

protoc --go_out=. *.proto

下面寫個例子說明一下,編寫的proto檔案内容如下

syntax = "proto3";

message GrpcResponse {
    int32 Result = 1;
    string Error = 2;
}

message GrpcRequest {
    string RequestType=1;
    int32 A = 2;
    int32 B = 3;
}

service GrpcService {
    rpc Add(GrpcRequest) returns (GrpcResponse) {}
    rpc    Subtract(GrpcRequest) returns (GrpcResponse) {}
    rpc    Multiply(GrpcRequest) returns (GrpcResponse) {}
    rpc    Divide(GrpcRequest) returns (GrpcResponse) {}
}
           

執行指令後,會多出一個.pb.go的檔案

如果一個.proto檔案中有包聲明,生成的源代碼将會使用它來作為Go的包名,如果.proto的包名中有. 在Go包名中會将.轉換為_。舉例來說proto包名example.high_score将會生成Go包名example_high_score。

在.proto檔案中可以使用option go_package指令來覆寫上面預設生成Go包名的規則。比如說包含如下指令的一個.proto檔案

package example.high_score; option go_package = "hs";

生成的Go源代碼的包名是hs。

如果一個.proto檔案中不包含package聲明,生成的源代碼将會使用.proto檔案的檔案名(去掉擴充名)作為Go包名,.會被首先轉換為_。舉例來說一個名為high.score.proto不包含package聲明的檔案将會生成檔案high.score.pb.go,他的Go包名是high_score。

參考:

https://zhuanlan.zhihu.com/p/83010418

https://www.jianshu.com/p/bd26be0109be

https://geektutu.com/post/quick-go-protobuf.html

https://blog.csdn.net/VBVSPER/article/details/91878373