Google Protocol Buffer with Golang

了解 Google Protocol Buffer

官网

Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.

下载二进制文件

https://github.com/google/protobuf/releases

配置环境

GOPATH

命令行输入:

1
go dev

或者在系统环境变量里添加一条GOPATH指向你的自定义目录。

最后将$GOPATH添加到系统环境变量path中。

可执行文件加入$GOPATH

以Windows为例,将下载的压缩包的bin目录下的protoc.exe复制到你的任意path路径下,我放到$GOPATH/bin目录下。

添加Go语言支持

命令行执行以下命令:

1
go get -u github.com/golang/protobuf/protoc-gen-go

代码生成

先编写一个addressbook.proto文件

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
syntax = "proto3";
package tutorial;
message Person {
string name = 1;
int32 id = 2; // Unique ID number for this person.
string email = 3;

enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}

message PhoneNumber {
string number = 1;
PhoneType type = 2;
}

repeated PhoneNumber phones = 4;
}

// Our address book file is just one of these.
message AddressBook {
repeated Person people = 1;
}

命令行输入以下生成命令:

1
2
protoc --go_out=./ ./addressbook.proto
# 命令格式 protoc -I=$SRC_DIR --go_out=$DST_DIR $SRC_DIR/addressbook.proto

在当前目录下生成addressbook.pb.go文件