基于Go语言的protobuf 安装 以及简单测试用例
先去官网下载protobuf的源码
https://github.com/google/protobuf/releases
可以先下载本地,然后上传到虚拟机中
我选择的是Source code(tar.gz)
安装依赖包(如果缺少包,可能会报错)
yum install -y gcc gcc-c++ autoconf automake libtool curl make g++ unzip
解压后,进入protobuf-3.5.1目录中,运行
./autogen.sh命令
执行./configure命令
make&& make install
检测protobuf是否安装成功?
protoc -h
由于要使用Go语言,因此,需要安装相应的插件
先去官网将插件×××到本地:
https://github.com/golang/protobuf/releases
上传到虚拟机,进行解压
tar -zxvf protobuf-1.1.0.tar.gz
重命名
mv protobuf-1.1.0.tar.gz protobuf
查询GOROOT的值是什么,如我的是:
echo$GOROOT
/usr/local/gohome/go
在GOROOT目录下,创建下面的目录src/github.com/golang
mkdir -p /usr/local/gohome/go/src/github.com/golang
将protobuf目录移动到$GOROOT/src/github.com/golang 目录下
进入$GOROOT/src/github.com/golang/protobuf
make install
举例:
先手动创建一个文件test.proto
//指定版本//注意proto3与proto2的写法有些不同syntax="proto3";//包名,通过protoc生成时go文件时packagetest;//手机类型//枚举类型第一个字段必须为0enumPhoneType{HOME=0;WORK=1;}//手机messagePhone{PhoneTypetype=1;stringnumber=2;}//人messagePerson{//后面的数字表示标识号int32id=1;stringname=2;//repeated表示可重复//可以有多个手机repeatedPhonephones=3;}//联系簿messageContactBook{repeatedPersonpersons=1;}
执行下面的命令,生成相应的代码文件
protoc --go_out=. *.proto
或者
protoc --go_out=. test.proto
Go语言中,如何使用呢?
1、首先创建test包,然后将生成的test.pb.go 上传到test包下
2、编写测试用例
内容如下:
packagemainimport("fmt""github.com/golang/protobuf/proto""io/ioutil""os""xingej-go/xingej-go/xingej-go666/protobuf/test")funcwrite(){p1:=&test.Person{Id:1,Name:"spark",}book:=&test.ContactBook{}book.Persons=append(book.Persons,p1)//编码数据data,_:=proto.Marshal(book)//将数据写入文件ioutil.WriteFile("./pb_test.txt",data,os.ModePerm)}funcread(){data,_:=ioutil.ReadFile("./pb_test.txt")book:=&test.ContactBook{}//解码数据proto.Unmarshal(data,book)for_,v:=rangebook.Persons{fmt.Println(v.Id,v.Name)}}funcmain(){write()read()}
本文测试样例,参考了下面的文章:
https://www.cnblogs.com/jkko123/p/7161843.html
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。