1. 編譯安裝protobuf(protobuf 沒有關(guān)于go的release)
為了從源碼安裝protobuf,先要安裝一些工具:包括autoconf、automake、libtool、curl(用于下載gmock)、make、 g++、 unzip。
在ubuntu可以使用如下命令安裝這些依賴:
sudo apt-get install autoconf automake libtool curl make g++ unzip
然后使用 git clone https://github.com/google/protobuf命令下載protobuf的源碼包。
接者使用命令 cd protobuf進入源碼庫中
然后使用 ./autogen.sh運行腳本生成需要的配置腳本
接著執(zhí)行如下的一系列命令來編譯安裝protocol buffer的complier
./configure
make
make check
sudo make install
sudo ldconfig
最后的一個命令是用于刷新共享庫的緩存的。,最后一個命令我的ubuntu無法執(zhí)行
2. 安裝proto-gen-go
命令如下: go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
然后將環(huán)境變量GOPATH定義的目錄下的bin目錄加入到環(huán)境變量PATH中。
命令如下:vi ~/.bashrc
然后在該文件最后加上:export PATH="$PATH:$GOPATH/bin"即可。
然后調(diào)用 source ~/.bashrc
3.定義一個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;
}
}
在該文件對應(yīng)的文件夾中執(zhí)行命令:protoc --go_out=. *.proto用于生成.pb.go文件。如果這個命令執(zhí)行過程中出現(xiàn) protoc-gen-go: program not found or is not executable 這個錯誤,表示該protoc-gen-go沒有被加入到Path環(huán)境變量中,應(yīng)該把該文件的所在目錄加入Path變量中。該文件存放在環(huán)境變量GOPATH目錄下的bin子目錄里。
4.編寫測試代碼:
首先要將上一節(jié)生成的example包放入GOPATH目錄下的src文件夾下:
然后建立如下的測試代碼:
package main
import (
"fmt"
"github.com/golang/protobuf/proto"
// test.pb.go 的路徑
"example"
)
func main() {
// 創(chuàng)建一個消息 Test
test := &example.Test{
// 使用輔助函數(shù)設(shè)置域的值
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 {
fmt.Println("marshaling error: ", err)
}
// 進行解碼
newTest := &example.Test{}
err = proto.Unmarshal(data, newTest)
if err != nil {
fmt.Println("unmarshaling error: ", err)
}
// 測試結(jié)果
if test.GetLabel() != newTest.GetLabel() {
fmt.Println("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
fmt.Printf("%+v", newTest)
}
5 golang中可用的protobuf的接口:
在使用之前,我們先了解一下每個 Protobuf 消息在 Golang 中有哪一些可用的接口:
1. 每一個 Protobuf 消息對應(yīng)一個 Golang 結(jié)構(gòu)體
2. 消息中域名字為 camel_case 在對應(yīng)的 Golang 結(jié)構(gòu)體中為 CamelCase
3. 消息對應(yīng)的 Golang 結(jié)構(gòu)體中不存在 setter 方法,只需要直接對結(jié)構(gòu)體賦值即可,賦值時可能使用到一些輔助函數(shù),例如:
msg.Foo = proto.String("hello")
4. 消息對應(yīng)的 Golang 結(jié)構(gòu)體中存在 getter 方法,用于返回域的值,如果域未設(shè)置值,則返回一個默認值
5. 消息中非 repeated 的域都被實現(xiàn)為一個指針,指針為 nil 時表示域未設(shè)置消息中 repeated 的域被實現(xiàn)為 slice
6. 訪問枚舉值時,使用“枚舉類型名_枚舉名”的格式(更多內(nèi)容可以直接閱讀生成的源碼)
7. 使用 proto.Marshal 函數(shù)進行編碼,使用 proto.Unmarshal 函數(shù)進行解碼
參考鏈接:
- 在 Golang 中使用 Protobuf
- golang [C++ installation](C++ Installation - Unix)
- go語言使用protobuf