1、安装:
(1)下载protc 编译器
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip
解压到protc目录
unzip protoc-3.6.1-linux-x86_64.zip -d protoc
cd /protoc/bin
配置环境
ln -s protoc /usr/bin/protoc
(2).获取 goprotobuf 提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能
go get github.com/golang/protobuf/proto
cd github.com/golang/protobuf/proto
go build
go install
2、使用
(1)编写proto文件,proto目录下的hi.proto
//指定版本
//注意proto3与proto2的写法有些不同
syntax = "proto3";
//包名,通过protoc生成时go文件时
package proto;
//priceNode
message PriceNode {
uint64 price = 1;
uint64 volume = 2;
uint64 level = 3;
uint64 orderLen = 4;
repeated uint64 order = 5;
}
//行情记录
message QuoteRecord {
uint64 marketDatetime = 1;
string stockCode = 2;
repeated PriceNode buyPrice = 3;
repeated PriceNode sellPrice = 4;
}
(2)将proto文件转为go文件
protoc --go_out=. *.proto
生成hi.pb.go文件
(3)编解码例子
func main() {
node:=&hi.PriceNode{Price:1,Volume:2,Level:3,OrderLen:4}
fmt.Println(node)
binData,err :=proto.Marshal(node)
if err!=nil{
fmt.Println(err.Error())
return
}
fmt.Println(string(binData))
node2 :=&hi.PriceNode{}
proto.Unmarshal(binData,node2)
fmt.Println(node2)
}