golang使用protobuf

释放双眼,带上耳机,听听看~!

安装protobuf编译工具

下载最新版

https://github.com/golang/protobuf

官方网站 https://developers.google.com/protocol-buffers/docs/proto3

解压后 执行


1
2
3
4
5
6
1./autogen.sh
2    如碰到没有支持的程序,安装之
3./configure
4make
5make install
6

安装golang支持库

下载 https://github.com/golang/protobuf

在项目src目录中建目录


1
2
1    github.com/golang/protobuf/
2

1
2
1将下载的protobuf全部copy到此目录
2

cd到此目录执行


1
2
3
1    make
2
3

1
2
1将编译出protoc-gen-go可执行程序,此程序提供给protobuf编译工具使用
2

测试

在代码目录中创建一个放置proto文件的文件夹,如 protocfg

创建.proto文件 配置protobuf数据结构如


1
2
3
4
5
6
7
8
9
10
11
1syntax = "proto3";
2package prototest;
3
4enum FOO { X = 0; };
5
6message Test {
7   string label = 1;
8   int32 type = 2 ;
9   int64 reps = 19;
10}
11

1
2
1在此目录执行
2

1
2
1/usr/local/bin/protoc --plugin={补齐}bin/protoc-gen-go --go_out=. test.proto
2

1
2
1将会生成 test.bp.go  此文件在go程序中使用:
2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1package main
2
3import (
4   "demo/prototest"
5   "fmt"
6   "libs/plog"
7
8   "github.com/golang/protobuf/proto"
9)
10
11func Test() {
12  fmt.Println("begin TestLog ...")
13  //proto.Bool(false)
14
15  test := &prototest.Test{Label: "hello", Type: 17, Reps: 34}
16  data, err := proto.Marshal(test)
17  if err != nil {
18      plog.Println(plog.Warning, "demo", err.Error())
19  } else {
20      unTest := &prototest.Test{}
21      err := proto.Unmarshal(data, unTest)
22      if err == nil {
23          fmt.Println("undata ", unTest.Label, unTest.Reps, unTest.Type)
24      }
25  }
26  fmt.Println("data", data)
27}
28
29func main() {
30  Test()
31}
32
33

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

安全运维

hadoop实战(一) hadoop基本概念

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索