官方網址:
https://developers.google.com/protocol-buffers/ (需要翻牆)
代碼倉庫:
https://github.com/google/protobuf (C++)
https://github.com/golang/protobuf (Golang)
https://developers.google.com/protocol-buffers/docs/gotutorial (英文版教程)
本文以下部分按照英文版教程操作(windows OS):
- 下載編譯器,下載頁面 https://github.com/google/protobuf/releases
最新發布版為V3.2.0,Url:https://github.com/google/protobuf/releases/download/v3.2.0/protoc-3.2.0-win32.zip
2. 在cmd中運行如下命令,(前提:golang環境已經正確配置)
go get -u github.com/golang/protobuf/protoc-gen-go
下載完成在,在$GOPATH\src\github.com\golang\protobuf中可以查看源碼
在$GOPATH\bin中可以找到生成的protoc-gen-go.exe,這是golang版的編譯插件。
要保證$GOPATH\bin目錄在環境變量$PATH中,這樣protoc.exe就可以找到這個插件了。
通過以上兩步,就完成了protobuf的golang編譯環境准備。
下面將以源碼包中的example代碼為例進行編譯。在https://github.com/google/protobuf/releases 頁面下載V3.2.0版本的源碼。
https://github.com/google/protobuf/archive/v3.2.0.zip
將壓縮包解壓到 D:\protobuf-3.2.0
D:\protobuf-3.2.0\examples 目錄包含了golang示例代碼。在該目錄下創建名為tutorial的文件夾,將addressbook.proto移動到tutorial文件夾下,將前面下載的protoc.exe也拷貝到該目錄下。
在命令行中,切換到D:\protobuf-3.2.0\examples\tutorial,執行命令
protoc --go_out=.\ addressbook.proto
生成 addressbook.pb.go 源文件,
修改 D:\protobuf-3.2.0\examples\add_person.go,將pb "github.com/google/protobuf/examples/tutorial"改為
pb "./tutorial"
命令行切換到D:\protobuf-3.2.0\examples目錄執行,go build add_person.go
在該目錄下生成了 add_person.exe
命令行執行 add_person.exe .\book.bin
按照提示,輸入相關信息,錄入完成后,數據被序列化到book.bin二進制文件中。
編譯list_people.go,執行 list_people.exe .\book.bin命令可以查看反序列化之后的信息。