您的位置 首页 golang

golang 中使用protobuf协议(资料篇)

在所有 网络通信协议 中,protobuf协议可以说最优秀的,封装的字节流最少(减少前后端io流的量),解析速度也是最快的(提交了服务器响应速度),跨语言方面也是很强大的,现在几乎所有的 编程语言 都支持它。但是也是通信协议中最难的一种,今天就整理一份golang中使用protobuf的资料。

安装protoc

下载地址:找到最新版本protoc(目前最新v3.7.1)。

包解压文件中 bin 中有protoc. exe 复制备用。

生成protoc-gen-go(手动生成)

下载地址:

包解压进入protobuf-master\protoc-gen-go 执行go build就会生成protoc-gen-go.exe可以执行文件。

将protoc.exe 和protoc-gen-go.exe复制在一个文件下面。

以上准备工作就做完了,正式开启协议内容proto文件(演示协议如下)

package test;
message  Msg {
 required string name=1; //姓名
 required int32 age=2; //年龄
 required string  Address  =3; //地址
}
 

cmd命令行中:protoc.exe –go_out=. ./test.proto生成golang需要*.pd.go代码文件,将这个文件复制到项目中。

写一个测试这个协议的go代码:

package main
import (
 "fmt"
 "httpServer/test/proto"
 "httpServer/test/proto_go"
)
func main() {
 fmt.Print("****")
 var name string="今日头条";
 var age int32=1;
 var  address  string="北京";
 //封装proto  byte []
  msg :=&proto_go.Msg{
 Name:&name,
 Age:&age,
 Address:&address,
 }
 var data, err = proto.Marshal(msg); //获得byte[]
 if(err!= nil ){
 fmt.Println(err)
 }
 //解析proto byte[] 流
 fmt.Println(data)
 var readObject proto_go.Msg
 error:=proto.Unmarshal(data,&readObject)
 if(error==nil) {
 fmt.Println(*readObject.Name, *readObject.Age, *readObject.Address)
 }
}
 

验证代码运行:

****[10 12 228 187 138 230 151 165 229 164 180 230 157 161 16 1 26 6 229 140 151 228 186 172]
今日头条 1 北京
 

可能遇到问题:

运行时,提示

这样错误提醒,没有关系,盘它。远程的访问不到,就访问本地的,在刚刚protobuf-master\protoc-gen-go的上级目录中有proto的文件,直接复制到自己项目中,然后将这个改成自己目录就可以了。

基本上golang中使用protobuf协议就没有问题了。

感谢github,golang ,protobuf。

文章来源:智云一二三科技

文章标题:golang 中使用protobuf协议(资料篇)

文章地址:https://www.zhihuclub.com/88674.shtml

关于作者: 智云科技

热门文章

网站地图