在 Golang 中使用 Protobuf


wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz
tar zxvf protobuf-2.6.1.tar.gz cd protobuf-2.6.1
./configure make make install protoc   -h

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

cd github.com/golang/protobuf/protoc-gen-go

go build

go install

vi /etc/profile 將$GOPATH/bin 加入環境變量

source profile

go get github.com/golang/protobuf/proto
cd github.com/golang/protobuf/proto
go build
go install

使用 goprotobuf
這里通過一個例子來說明用法。先創建一個 .proto 文件 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; } }

 


編譯此 .proto 文件:

protoc --go_out=. *.proto

 

這里通過 –go_out 來使用 goprotobuf 提供的 Protobuf 編譯器插件 protoc-gen-go。這時候我們會生成一個名為 test.pb.go 的源文件。

在使用之前,我們先了解一下每個 Protobuf 消息在 Golang 中有哪一些可用的接口:

  1. 每一個 Protobuf 消息對應一個 Golang 結構體

  2. 消息中域名字為 camel_case 在對應的 Golang 結構體中為 CamelCase

  3. 消息對應的 Golang 結構體中不存在 setter 方法,只需要直接對結構體賦值即可,賦值時可能使用到一些輔助函數,例如:

    msg.Foo = proto.String("hello")
  4. 消息對應的 Golang 結構體中存在 getter 方法,用於返回域的值,如果域未設置值,則返回一個默認值

  5. 消息中非 repeated 的域都被實現為一個指針,指針為 nil 時表示域未設置

  6. 消息中 repeated 的域被實現為 slice

  7. 訪問枚舉值時,使用“枚舉類型名_枚舉名”的格式(更多內容可以直接閱讀生成的源碼)

  8. 使用 proto.Marshal 函數進行編碼,使用 proto.Unmarshal 函數進行解碼


現在我們編寫一個小程序:

package main

import (    "log"
    // 輔助庫
    "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"),
        },
    }    // 進行編碼
    data, err := proto.Marshal(test)    
  if err != nil {         log.Fatal("marshaling error: ", err)     }    // 進行解碼     newTest := &example.Test{}     err = proto.Unmarshal(data, newTest)    
  if err != nil {         log.Fatal("unmarshaling error: ", err)     }    // 測試結果     if test.GetLabel() != newTest.GetLabel() {         log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())     } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM