[Go]Golang引入Protobuffer

准备

在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"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值