如何在Go中使用Protobuf

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

Protobuf對於Golang通過外掛程式進行支援,因些需要安裝protoc的執行環境,下面我們來一步步看下,如何搭建一個編譯環境。


1. 安裝protoc


2. 下載並安裝protobuf-go外掛程式

從github上下載外掛程式,並解壓(https://github.com/golang/protobuf),得到以下的目錄

drwxr-xr-x 6 root root 4096 Jun 16 15:45 .drwxr-xr-x 3 root root 4096 Jun 16 15:48 ..-rw-r--r-- 1 root root  173 Jun 15 06:31 AUTHORS-rw-r--r-- 1 root root  170 Jun 15 06:31 CONTRIBUTORSdrwxr-xr-x 3 root root 4096 Jun 15 06:31 jsonpb-rw-r--r-- 1 root root 1583 Jun 15 06:31 LICENSE-rw-r--r-- 1 root root 2080 Jun 15 06:31 Makefile-rw-r--r-- 1 root root 1955 Jun 15 06:31 Make.protobufdrwxr-xr-x 4 root root 4096 Jun 15 06:31 protodrwxr-xr-x 7 root root 4096 Jun 16 15:42 protoc-gen-godrwxr-xr-x 8 root root 4096 Jun 15 06:31 ptypes-rw-r--r-- 1 root root 7149 Jun 15 06:31 README.md

這時,執行make install,多半是不會成功的,一般會報找不到對應的檔案,原因在於go源檔案中指定的目錄位置是這樣的

import (    "io/ioutil"    "os"    "github.com/golang/protobuf/proto"    "github.com/golang/protobuf/protoc-gen-go/generator")

因此,要求我們把當面下載的檔案放到$GOROOT對應的目錄下,並且把目錄名改成指定的名稱,比如我的GOROOT=/usr/local/go,那我就把解壓後的目錄改名為protobuf,並在/usr/local/go下建立/usr/local/go/src/github.com/golang/目錄,把protobuf目錄整體mv過去,再執行make install,執行結果如下:

[root@SH-todo-1412181717 /usr/local/go/src/github.com/golang/protobuf]# make installgo install ./proto ./jsonpb ./ptypesgo install ./protoc-gen-go

說明執行成功了。

3. 用法舉例

下面我們來說明如何把*.proto檔案產生*.go檔案,同時在程式中序列及還原序列化

a) 建立一個test.proto檔案

package example;enum FOO { X = 17; };message Test {required string label = 1;optional int32 type = 2 [default=77];repeated int64 reps = 3;optional group OptionalGroup = 4 {required string RequiredField = 5;}}

執行protoc --go_out=. test.proto,得到test.pb.go

測試代碼如下:

package mainimport (    "log"    "fmt"    // 輔助庫    "github.com/golang/protobuf/proto"    // test.pb.go 的路徑    "example")func main() {    // 建立一個訊息 Test    test := &example.Test{        // 使用輔助函數設定域的值        Label: proto.String("hello"),        Type:  proto.Int32(17),        Optionalgroup: &example.Test_OptionalGroup{            RequiredField: proto.String("good bye"),        },    }    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())    *(test.Label) = "hello go"    *(test.Type) = 18    // 進行編碼    data, err := proto.Marshal(test)    if err != nil {        log.Fatal("marshaling error: ", err)    }    fmt.Printf("Binary Len:%d\n", len(data))    // 進行解碼    newTest := &example.Test{}    err = proto.Unmarshal(data, newTest)    if err != nil {        log.Fatal("unmarshaling error: ", err)    }    fmt.Printf("Label:%s Type:%d\n", test.GetLabel(), test.GetType())    // 測試結果    if test.GetLabel() != newTest.GetLabel() {        log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())    }}

執行結果如下:

Label:hello Type:17Binary Len:24Label:hello go Type:18


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.