golang中使用protobuf
安装 goprotobuf
1.从 https://github.com/google/protobuf/releases获取 Protobuf编译器 protoc(可下载到 Windows下的二进制版本 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- ./configure make make install protoc -h
2.获取 goprotobuf提供的 Protobuf编译器插件 protoc-gen-go(被放置于 $GOPATH/bin下,$GOPATH/bin应该被加入 PATH环境变量,以便 protoc能够找到 protoc-gen-go) 此插件被protoc 使用,用于编译.proto 文件为Golang 源文件,通过此源文件可以使用定义在.proto 文件中的消息。 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
3.获取 goprotobuf提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能 get github.com/golang/protobuf/proto
cd github.com/golang/protobuf/proto
go build
go install
使用 goprotobuf package example;
enum FOO { X = 17; };
message Test {
required string label = ;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
protoc --go_out=. *.proto
这里通过 –go_out 来使用 goprotobuf 提供的 Protobuf 编译器插件 protoc-gen-go。这时候我们会生成一个名为 test.pb.go 的源文件。 在使用之前,我们先了解一下每个 Protobuf 消息在 Golang 中有哪一些可用的接口:
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(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)
unmarshaling error: 测试结果
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf(data mismatch %q != %q(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |