无需预编译 Go 代码:将 protobuf 消息序列化为 JSON
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《无需预编译 Go 代码:将 protobuf 消息序列化为 JSON》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
我想将 protobuf 序列化消息转换为人类可读的 json 格式。我面临的主要问题是我需要在不事先将原型描述符编译成 go 代码的情况下执行此操作。我可以在运行时访问 .proto
文件,但不能在编译时访问。
我的印象是新的 protobuf api v2 (https://github.com/protocolbuffers/protobuf-go) 支持动态反序列化(参见包 types/dynamicpb
),但我不知道如何使用它显然:
func readDynamically(in []byte) { // How do I load the required descriptor (for NewMessage()) from my `addressbook.proto` file?) descriptor := ?? msg := dynamicpb.NewMessage(descriptor) err := protojson.Unmarshal(in, msg) if err != nil { panic(err) } }
上面的代码注释了我的问题:如何从 .proto
文件获取 dynamicpb.newmessage()
所需的描述符?
解决方案
对于 dynamicpb 包来说应该像这样工作。
func readdynamically(in []byte) { registry, err := createprotoregistry(".", "addressbook.proto") if err != nil { panic(err) } desc, err := registry.findfilebypath("addressbook.proto") if err != nil { panic(err) } fd := desc.messages() addressbook := fd.byname("addressbook") msg := dynamicpb.newmessage(addressbook) err = proto.unmarshal(in, msg) jsonbytes, err := protojson.marshal(msg) if err != nil { panic(err) } fmt.println(string(jsonbytes)) if err != nil { panic(err) } } func createprotoregistry(srcdir string, filename string) (*protoregistry.files, error) { // create descriptors using the protoc binary. // imported dependencies are included so that the descriptors are self-contained. tmpfile := filename + "-tmp.pb" cmd := exec.command("./protoc/protoc", "--include_imports", "--descriptor_set_out=" + tmpfile, "-i"+srcdir, path.join(srcdir, filename)) cmd.stdout = os.stdout cmd.stderr = os.stderr err := cmd.run() if err != nil { return nil, err } defer os.remove(tmpfile) marshalleddescriptorset, err := ioutil.readfile(tmpfile) if err != nil { return nil, err } descriptorset := descriptorpb.filedescriptorset{} err = proto.unmarshal(marshalleddescriptorset, &descriptorset) if err != nil { return nil, err } files, err := protodesc.newfiles(&descriptorset) if err != nil { return nil, err } return files, nil }
这个问题有点意思。我已经在 protobuf 插头上做了一些工作。据我所知,需要额外的 cli,因为我们不想“重新发明轮子”。
第一步,我们需要 protoc 将“.proto”文件转换为某种格式,以便我们可以轻松获得“protoreflect.messagedescriptor”。
该插件用于获取原始字节,原始字节由 protoc 发送到其他插件作为输入。
package main import ( "fmt" "io/ioutil" "os" ) func main() { if len(os.args) == 2 && os.args[1] == "--version" { // fmt.fprintf(os.stderr, "%v %v\n", filepath.base(os.args[0]), version.string()) os.exit(0) } in, err := ioutil.readall(os.stdin) if err != nil { fmt.printf("error: %v", err) return } ioutil.writefile("./out.pb", in, 0755) }
构建并重命名为protoc-gen-raw
,然后生成protoc --raw_out=./pb ./server.proto
,你将得到out.pb
。从现在开始忘记你的“.proto”文件,并将这个“out.pb”放在你打算放置“.proto”的地方。我们得到的是这个 .pb 文件的官方支持。
第 2 步:将 protobuf 序列化消息反序列化为 json。
package main import ( "fmt" "io/ioutil" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/dynamicpb" "google.golang.org/protobuf/types/pluginpb" ) func main() { in, err := ioutil.ReadFile("./out.pb") if err != nil { fmt.Printf("failed to read proto file: %v", err) return } req := &pluginpb.CodeGeneratorRequest{} if err := proto.Unmarshal(in, req); err != nil { fmt.Printf("failed to unmarshal proto: %v", err) return } gen, err := protogen.Options{}.New(req) if err != nil { fmt.Printf("failed to create new plugin: %v", err) return } // serialize protobuf message "ServerConfig" data := &ServerConfig{ GameType: 1, ServerId: 105, Host: "host.host.host", Port: 10024, } raw, err := data.Marshal() if err != nil { fmt.Printf("failed to marshal protobuf: %v", err) return } for _, f := range gen.Files { for _, m := range f.Messages { // "ServerConfig" is the message name of the serialized message if m.GoIdent.GoName == "ServerConfig" { // m.Desc is MessageDescriptor msg := dynamicpb.NewMessage(m.Desc) // unmarshal []byte into proto message err := proto.Unmarshal(raw, msg) if err != nil { fmt.Printf("failed to Unmarshal protobuf data: %v", err) return } // marshal message into json jsondata, err := protojson.Marshal(msg) if err != nil { fmt.Printf("failed to Marshal to json: %v", err) return } fmt.Printf("out: %v", string(jsondata)) } } } } // the output is: // out: {"gameType":1, "serverId":105, "host":"host.host.host", "port":10024}
今天关于《无需预编译 Go 代码:将 protobuf 消息序列化为 JSON》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

- 上一篇
- 如何在 Wasm 中调用 JavaScript 外部函数?

- 下一篇
- Python Logging 模块与其他编程语言的集成
-
- Golang · Go问答 | 12个月前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 12个月前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 20次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 29次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 35次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 43次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 36次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览