无需预编译 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问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 201次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 204次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 201次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 208次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 224次使用
-
- 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浏览