在 Golang 中使用 Protobuf
|
安装 goprotobuf
1.从 https://github.com/google/protobuf/releases获取 Protobuf编译器 protoc(可下载到 Windows下的二进制版本 wgethttps://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gztarzxvfprotobuf-2.6.1.tar.gz cdprotobuf-2.6.1./configure make makeinstall protoc-h
2.获取 goprotobuf提供的 Protobuf编译器插件 protoc-gen-go(被放置于 $GOPATH/bin下,$GOPATH/bin应该被加入 PATH环境变量,以便 protoc能够找到 protoc-gen-go) 此插件被protoc 使用,用于编译.proto 文件为Golang 源文件,通过此源文件可以使用定义在.proto 文件中的消息。 gogetgithub.com/golang/protobuf/protoc-gen-go cdgithub.com/golang/protobuf/protoc-gen-go gobuild goinstall vi/etc/profile将$GOPATH/bin加入环境变量 sourceprofile 3.获取 goprotobuf提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能 gogetgithub.com/golang/protobuf/proto cdgithub.com/golang/protobuf/proto gobuild goinstall 使用 goprotobuf packageexample;enumFOO{X=17;};
messageTest{
requiredstringlabel=1;
optionalint32type=2[default=77];
repeatedint64reps=3;
optionalgroupOptionalGroup=4{
requiredstringRequiredField=5;
}
}
protoc--go_out=.*.proto 这里通过 –go_out 来使用 goprotobuf 提供的 Protobuf编译器插件 protoc-gen-go。这时候我们会生成一个名为 test.pb.go 的源文件。 在使用之前,我们先了解一下每个 Protobuf 消息在 Golang 中有哪一些可用的接口:
packagemain
import("log"
//辅助库
"github.com/golang/protobuf/proto"
//test.pb.go的路径
"example")
funcmain(){//创建一个消息Test
test:=&example.Test{//使用辅助函数设置域的值
Label:proto.String("hello"),Type:proto.Int32(17),Optionalgroup:&example.Test_OptionalGroup{
RequiredField:proto.String("goodbye"),},}//进行编码
data,err:=proto.Marshal(test)iferr!=nil{
log.Fatal("marshalingerror:",err)
}//进行解码
newTest:=&example.Test{}
err=proto.Unmarshal(data,newTest)iferr!=nil{
log.Fatal("unmarshalingerror:",err)
}//测试结果
iftest.GetLabel()!=newTest.GetLabel(){
log.Fatalf("datamismatch%q!=%q",test.GetLabel(),newTest.GetLabel())
}
}
转帖:http://my.oschina.net/ifraincoat/blog/510971 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
