這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
安裝protobuf編譯工具
下載最新版https://github.com/golang/protobuf官方網站 https://developers.google.com/protocol-buffers/docs/proto3解壓後 執行
./autogen.sh 如碰到沒有支援的程式,安裝之./configuremakemake install
安裝golang支援庫
下載 https://github.com/golang/protobuf在項目src目錄中建目錄
github.com/golang/protobuf/
將下載的protobuf全部copy到此目錄cd到此目錄執行
make
將編譯出protoc-gen-go可執行程式,此程式提供給protobuf編譯工具使用
測試
在代碼目錄中建立一個放置proto檔案的檔案夾,如 protocfg建立.proto檔案 配置protobuf資料結構如
syntax = "proto3";package prototest;enum FOO { X = 0; };message Test {string label = 1;int32 type = 2 ;int64 reps = 19;}在此目錄執行
/usr/local/bin/protoc --plugin={補齊}bin/protoc-gen-go --go_out=. test.proto將會產生 test.bp.go 此檔案在go程式中使用:
package mainimport ("demo/prototest""fmt""libs/plog""github.com/golang/protobuf/proto")func Test() {fmt.Println("begin TestLog ...")//proto.Bool(false)test := &prototest.Test{Label: "hello", Type: 17, Reps: 34}data, err := proto.Marshal(test)if err != nil {plog.Println(plog.Warning, "demo", err.Error())} else {unTest := &prototest.Test{}err := proto.Unmarshal(data, unTest)if err == nil {fmt.Println("undata ", unTest.Label, unTest.Reps, unTest.Type)}}fmt.Println("data", data)}func main() {Test()}