go protobuf

介绍

Protocol buffers通常称为Protobuf,是Google开发的一种协议,允许对结构化数据进行序列化和反序列化。 谷歌开发它的目的是提供一种比XML更好的方式来进行系统间通信。 因此,他们专注于使其比XML更简单,更小,更快,更易于维护。与此同时,该协议甚至超越了JSON,具有更好的性能,更好的可维护性和更小的尺寸。

安装

  • 下载 protoc 放到 GOPATH/bin

    测试

    1
    protoc --version
  • proto的go插件

    1
    go get github.com/golang/protobuf/protoc-gen-go
  • 安装goprotobuf库

    1
    go get github.com/golang/protobuf/proto

编写*.proto 文件

1
2
3
4
5
6
7
8
syntax = "proto3";  //指定版本,必须要写(proto3、proto2)
package example;

message MessageInfo{
string message = 1; //消息
int32 length = 2; //消息大小
int32 cnt = 3; //消息计数
}

如果放在 package main 下,运行时会报错

1
2
3
# command-line-arguments
./main.go:10:11: undefined: UserInfo
./main.go:17:14: undefined: UserInfo

生成go文件

1
protoc --go_out=. *.proto

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func main() {
test := &example.MessageInfo{
Message: "hello world",
Length: 100,
Cnt: 3,
}

data, _ := proto.Marshal(test)
newTest := &example.MessageInfo{}
err := proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal(err)
}
fmt.Printf("test :%+v\n", test)
fmt.Printf("newTest :%+v\n",newTest)
}

结果:

1
2
test :message:"hello world" length:100 cnt:3 
newTest :message:"hello world" length:100 cnt:3

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!