安装protobuf编译工具
下载最新版
https://github.com/golang/protobuf
官方网站 https://developers.google.com/protocol-buffers/docs/proto3
解压后 执行
./autogen.sh
如碰到没有支持的程序,安装之
./configure
make
make install
安装golang支持库
下载 https://github.com/golang/protobuf
在项目src目录中建目录
github.com/golang/protobuf/
将下载的protobuf全部copy到此目录
cd到此目录执行
make
将编译出protoc-gen-go可执行程序,此程序提供给protobuf编译工具使用
测试
在代码目录中创建一个放置proto文件的文件夹,如 protocfg
创建.proto文件 配置protobuf数据结构如
syntax = "proto3";
package prototest;
enum FOO { X = 0; };
message Test {
string label = 1;
int32 type = 2 ;
int64 reps = 19;
}
在此目录执行
/usr/local/bin/protoc --plugin={补齐}bin/protoc-gen-go --go_out=. test.proto
将会生成 test.bp.go 此文件在go程序中使用:
package main
import (
"demo/prototest"
"fmt"
"libs/plog"
"github.com/golang/protobuf/proto"
)
func Test() {
fmt.Println("begin TestLog ...")
//proto.Bool(false)
test := &prototest.Test{Label: "hello", Type: 17, Reps: 34}
data, err := proto.Marshal(test)
if err != nil {
plog.Println(plog.Warning, "demo", err.Error())
} else {
unTest := &prototest.Test{}
err := proto.Unmarshal(data, unTest)
if err == nil {
fmt.Println("undata ", unTest.Label, unTest.Reps, unTest.Type)
}
}
fmt.Println("data", data)
}
func main() {
Test()
}