准备
在Golang中使用Protobuffer非常简单。
1.安装protobuffer的环境
你可以选择直接github上下载proto源码然后自行编译,这部分教程一大把不再赘述。
为了省心(偷懒),我打包了一份protobuffer2.6版本的release版,还包括给C#和Go使用的可执行程序。
连接在:protobuffer2.6下载
解压之后你会看到如下文件结构:
bin文件夹是protobuffer的realease目录:
其中:
- CodeGenerator.exe 是编译.proto并生成对应的C#代码的程序
- protoc-gen-go.exe 是编译.proto并生成对应的Go代码的程序
在主目录写了两个批处理文件:
//CreatePacket-CSharp.bat
bin\CodeGenerator.exe PBMessage.proto --output output\csharp --preserve-names
//PBMessage.proto是输入的PB描述文件
//--ouput是命令参数 后边紧跟输出代码的目录
//--perserve-names是表示生成的代码使用自己在.proto描述的名字
//CreatePacket-Go.bat
bin\protoc.exe --go_out=output\go PBMessage.proto
//PBMessage.proto是输入的PB描述文件
//--go_out是命令参数 后边紧跟输出代码的目录
这里我的PBMessage.proto的描述如下:
package ProtobufPacket;
message CG_LOGIN_IN
{
required int32 id = 1;
required string account = 2;
required string password = 3;
}
这里命名的package的名字是ProtobufPacket,对应的产生的go文件的packet名就是ProtobufferPacket,C#的命名空间是Protobuffer。
# 2.编译.proto文件
我们运行安装目录中的批处理文件,以go为例,我们得到名为PBMessage.pb.go的文件:
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: PBMessage.proto
/*
Package ProtobufPacket is a generated protocol buffer package.
It is generated from these files:
PBMessage.proto
It has these top-level messages:
CG_LOGIN_IN
*/
package ProtobufPacket
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"