ProtoBuf最近几年也算比较流行,它是一种语言无关,平台无关,并且可以扩展,并结构数据序列化的方法。相比JSON/XML这类文本格式的,ProtoBuf是二进制的,更快更高效。对于这么好的特性,Gin当然是支持的。
通过这篇文章你可以学到:
- ProtoBuf数据结构
- ProtoBuf对象如何生成Golang代码
- Gin服务端如何序列化ProtoBuf输出
- Go客户端如何反序列化ProtoBuf
- Gin关于ProtoBuf的源代码分析原理实现
- Gin Render机制分析
- Gin如何优雅的面向接口编程
ProtoBuf数据结构
.proto
这就是一个比较简单的ProtoBuf数据结构定义了,和我们在Golang里定义Struct差不多。
生成Golang代码
有了ProtoBuf结构数据,我们就可以生成对应的Golang代码了。
protocprotoc$PATH/bin
其次呢,因为ProtoBuf本身不支持GO语言,所以我们还得安装一个生成Golang代码的插件。安装方式也非常简单,通过如下代码即可:
user.proto
--go_out=.user.pb.gofilename.pb.go
User
User
在Gin中使用ProtoBuf
有了ProtoBuf对应的Golang代码,我们就可以在Gin使用了。
module.Userc.ProtoBufhttp://localhost:8080/protobuf
客户端反序列化ProtoBuf数据
反序列化也很简单,我们先启动上面的服务端 Protocol Buffer API 服务。
User{张三 20 {} [] 0}proto.UnmarshalMerge(body, user)
Gin ProtoBuf 源代码分析原理实现
那么Gin是如何实现ProtoBuf序列化的呢?我们从Gin的源代码分析上来看Gin比较优雅的实现,以及Gin的面向接口的编程。剩下的精彩内容请点击:
Golang Gin 实战(十二)| ProtoBuf 使用和源码分析原理实现mp.weixin.qq.com精彩文章推荐
Golang Gin 实战(十一)| HTML模板渲染
Golang Gin 实战(十)| XML渲染
Golang Gin 实战(九)| JSONP跨域和劫持
Golang Gin 实战(八)| JSON渲染输出
Golang Gin 实战(七)| 分组路由源代码分析
Golang Gin 实战(六)| 获取Form表单参数和原理分析
Golang Gin 实战(五)| 接收数组和map
Golang Gin 实战(四)| URL查询参数的获取和原理分析
Golang Gin 实战(三)| 路由参数
Golang Gin 实战(二)| 简便的Restful API 实现
Golang Gin 实战(一)| 快速安装入门
flysnow_org