golang使用protobuf

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

安裝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()}








聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.