转自:https://studygolang.com/articles/5753
安装 goprotobuf
1.从 https://github.com/google/protobuf/releases获取 Protobuf编译器 protoc(可下载到 Windows下的二进制版本
wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz tar zxvf protobuf-2.6.1.tar.gz cd protobuf- ./configure make make install protoc -h
2.获取 goprotobuf提供的 Protobuf编译器插件 protoc-gen-go(被放置于 $GOPATH/bin下,$GOPATH/bin应该被加入 PATH环境变量,以便 protoc能够找到 protoc-gen-go)
此插件被protoc 使用,用于编译.proto 文件为Golang 源文件,通过此源文件可以使用定义在.proto 文件中的消息。
3.获取 goprotobuf提供的支持库,包含诸如编码(marshaling)、解码(unmarshaling)等功能
使用 goprotobuf
这里通过一个例子来说明用法。先创建一个 .proto 文件 test.proto:
编译此 .proto 文件:
这里通过 –go_out 来使用 goprotobuf 提供的 Protobuf 编译器插件 protoc-gen-go。这时候我们会生成一个名为 test.pb.go 的源文件。
在使用之前,我们先了解一下每个 Protobuf 消息在 Golang 中有哪一些可用的接口:
- 每一个 Protobuf 消息对应一个 Golang 结构体
- 消息中域名字为 camel_case 在对应的 Golang 结构体中为 CamelCase
- 消息对应的 Golang 结构体中不存在 setter 方法,只需要直接对结构体赋值即可,赋值时可能使用到一些辅助函数,例如:
msg.Foo = proto.String("hello")
- 消息对应的 Golang 结构体中存在 getter 方法,用于返回域的值,如果域未设置值,则返回一个默认值
- 消息中非 repeated 的域都被实现为一个指针,指针为 nil 时表示域未设置
- 消息中 repeated 的域被实现为 slice
- 访问枚举值时,使用“枚举类型名_枚举名”的格式(更多内容可以直接阅读生成的源码)
- 使用 proto.Marshal 函数进行编码,使用 proto.Unmarshal 函数进行解码
本文来自:CSDN博客
感谢作者:u013923131
原文地址:https://www.jb51.cc/go/187400.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。