自定义选项在使用 protojson 库生成的 JSON 中不可见
使用 protojson 库生成的 JSON 中缺少自定义选项。本文探讨了如何使用 protoreflect 或 protojson 从 filedescriptorset 中提取自定义选项。虽然本文没有直接提供在生成的 JSON 中获取自定义选项的具体方法,但它提供了利用运行时填充的原型注册表来编组和解组选项的解决方案。这种方法涉及注册所有扩展类型并使用 protoreflect 反射来遍历扩展字段,从而获取自定义选项的值。
我正在尝试从 protoc 编译器生成的 filedescriptorset 中提取 protobuf 自定义选项。我无法使用 protoreflect 来做到这一点。因此,我尝试使用 protojson 库来做到这一点。
ps:导入 go 生成的代码不适合我的用例。
这是我正在测试的 protobuf 消息:
syntax = "proto3";
option go_package = "./protoze";
import "google/protobuf/descriptor.proto";
extend google.protobuf.fieldoptions {
string meta = 50000;
}
extend google.protobuf.fileoptions {
string food = 50001;
}
option (food) = "cheese";
message x {
int64 num = 1;
}
message p {
string fname = 1 [json_name = "fname"];
string lname = 2 [json_name = "0123", (meta) = "yo"];
string designation = 3;
repeated string email = 4;
string userid = 5;
string empid = 6;
repeated x z = 7;
}
// protoc --go_out=. filename.proto
这是我的进展:
package main
import (
"fmt"
"io/ioutil"
"os/exec"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
)
func main() {
exec.command("protoc", "-obinaryfile", "1.proto").run()
fset := descriptorpb.filedescriptorset{}
byts, _ := ioutil.readfile("file")
proto.unmarshal(byts, &fset)
byts, _ = protojson.marshal(fset.file[0])
fmt.println(string(byts))
}
这是输出 json
{
"name": "1.proto",
"dependency": [
"google/protobuf/descriptor.proto"
],
"messageType": [
{
"name": "X",
"field": [
{
"name": "num",
"number": 1,
"label": "LABEL_OPTIONAL",
"type": "TYPE_INT64",
"jsonName": "num"
}
]
},
{
"name": "P",
"field": [
{
"name": "Fname",
"number": 1,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"jsonName": "FNAME"
},
{
"name": "Lname",
"number": 2,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"jsonName": "0123",
"options": {}
},
{
"name": "Designation",
"number": 3,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"jsonName": "Designation"
},
{
"name": "Email",
"number": 4,
"label": "LABEL_REPEATED",
"type": "TYPE_STRING",
"jsonName": "Email"
},
{
"name": "UserID",
"number": 5,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"jsonName": "UserID"
},
{
"name": "EmpID",
"number": 6,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"jsonName": "EmpID"
},
{
"name": "z",
"number": 7,
"label": "LABEL_REPEATED",
"type": "TYPE_MESSAGE",
"typeName": ".X",
"jsonName": "z"
}
]
}
],
"extension": [
{
"name": "Meta",
"number": 50000,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"extendee": ".google.protobuf.FieldOptions",
"jsonName": "Meta"
},
{
"name": "Food",
"number": 50001,
"label": "LABEL_OPTIONAL",
"type": "TYPE_STRING",
"extendee": ".google.protobuf.FileOptions",
"jsonName": "Food"
}
],
"options": {
"goPackage": "./protoze"
},
"syntax": "proto3"
}
因此,有关我的自定义选项的数据显示在扩展中。但我真正想要的是“选项”中那些自定义选项的值。 (在我的例子中是(食物)=“奶酪”,我想要奶酪)
有人可以告诉我如何使用 protoreflect 或使用 protojson 从 filedescriptorset 中提取自定义选项。
我尝试了很多尝试使用 protoreflect 来提取它,但失败了!
解决方案
虽然不是具体回答如何在生成的 json 中获取自定义选项,但我相信我已经找到了听起来像您的基本问题的答案:如何在不加载生成的 go 代码的情况下访问自定义选项。这要感谢 dsnet 对我在 golang issues board 上的问题的回答。不用说,这个棘手的解决方案的所有功劳都归功于他。重点是使用运行时填充的原型注册表来编组和解组选项。实际上了解自定义选项的类型。
我对这种方法的工作原理进行了完整的演示 in this repo,关键部分(所有内容都来自 dsnet 的示例)在这里:
func main() {
protogen.Options{
}.Run(func(gen *protogen.Plugin) error {
gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
// The type information for all extensions is in the source files,
// so we need to extract them into a dynamically created protoregistry.Types.
extTypes := new(protoregistry.Types)
for _, file := range gen.Files {
if err := registerAllExtensions(extTypes, file.Desc); err != nil {
panic(err)
}
}
// run through the files again, extracting and printing the Message options
for _, sourceFile := range gen.Files {
if !sourceFile.Generate {
continue
}
// setup output file
outputfile := gen.NewGeneratedFile("./out.txt", sourceFile.GoImportPath)
for _, message := range sourceFile.Messages {
outputfile.P(fmt.Sprintf("\nMessage %s:", message.Desc.Name()))
// The MessageOptions as provided by protoc does not know about
// dynamically created extensions, so they are left as unknown fields.
// We round-trip marshal and unmarshal the options with
// a dynamically created resolver that does know about extensions at runtime.
options := message.Desc.Options().(*descriptorpb.MessageOptions)
b, err := proto.Marshal(options)
if err != nil {
panic(err)
}
options.Reset()
err = proto.UnmarshalOptions{Resolver: extTypes}.Unmarshal(b, options)
if err != nil {
panic(err)
}
// Use protobuf reflection to iterate over all the extension fields,
// looking for the ones that we are interested in.
options.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
if !fd.IsExtension() {
return true
}
outputfile.P(fmt.Sprintf("Value of option %s is %s",fd.Name(), v.String()))
// Make use of fd and v based on their reflective properties.
return true
})
}
}
return nil
})
}
// Recursively register all extensions into the provided protoregistry.Types,
// starting with the protoreflect.FileDescriptor and recursing into its MessageDescriptors,
// their nested MessageDescriptors, and so on.
//
// This leverages the fact that both protoreflect.FileDescriptor and protoreflect.MessageDescriptor
// have identical Messages() and Extensions() functions in order to recurse through a single function
func registerAllExtensions(extTypes *protoregistry.Types, descs interface {
Messages() protoreflect.MessageDescriptors
Extensions() protoreflect.ExtensionDescriptors
}) error {
mds := descs.Messages()
for i := 0; i < mds.Len(); i++ {
registerAllExtensions(extTypes, mds.Get(i))
}
xds := descs.Extensions()
for i := 0; i < xds.Len(); i++ {
if err := extTypes.RegisterExtension(dynamicpb.NewExtensionType(xds.Get(i))); err != nil {
return err
}
}
return nil
}
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《自定义选项在使用 protojson 库生成的 JSON 中不可见》文章吧,也可关注golang学习网公众号了解相关技术文章。
如何有效地将数据库结果存储在内存缓存中
- 上一篇
- 如何有效地将数据库结果存储在内存缓存中
- 下一篇
- 立即生效VSCode中文设置的方法
-
- Golang · Go问答 | 37分钟前 |
- Go Trim 为什么会多删字符:与 TrimPrefix 的区别
- 350浏览 收藏
-
- Golang · Go问答 | 11小时前 |
- Go 接口不等于 nil 却调用失败是什么原因
- 358浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go range 读 Channel 为什么收不住:从发送方生命周期补上结束信号
- 101浏览 收藏
-
- Golang · Go问答 | 1天前 |
- WalkDir 找到的是逻辑名不是磁盘路径:Go fs.FS 迁移后的安全转换
- 386浏览 收藏
-
- Golang · Go问答 | 1天前 |
- 短超时压测后 Goroutine 数量不回落:区分工作未取消与结果发送阻塞
- 265浏览 收藏
-
- Golang · Go问答 | 1天前 | 错误处理 · go · 工程实践 · Go fmt.Errorf errors.Is errors.As errors.Join errors
- 错误被 fmt.Errorf 包了几层还想分类:用 errors.Is、errors.As 和 Join 保留判断能力
- 184浏览 收藏
-
- Golang · Go问答 | 1天前 |
- 一项并发任务失败后如何让兄弟任务收敛:用 errgroup 组织首错与取消
- 397浏览 收藏
-
- Golang · Go问答 | 1天前 | 并发 · golang · Context · context (上下文) Go 协程 Go 函数
- Go 超时后任务还在运行:把 Context 传到真正执行 I/O 的那一层
- 323浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 152次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 84次使用
-
- ClickPrompt
- ClickPrompt是一款专为AI提示词编写者设计的开源在线工具,支持Stable Diffusion绘图、ChatGPT对话及GitHub Copilot代码辅助。提供Prompt自动生成、一键运行、社区分享及可视化优化功能,帮助用户高效获取精准AI输出。
- 41次使用
-
- PromptHero
- PromptHero是专业的AI提示词搜索引擎与优化平台,支持Stable Diffusion、Midjourney等主流模型。提供海量提示词库、分类搜索、在线课程及社区互动,助力用户高效生成高质量AI图像与文本。
- 24次使用
-
- Stable Diffusion Prompt Book
- 深入解析OpenArt推出的Stable Diffusion Prompt Book,这本免费的开源提示词指南涵盖从基础语法到高级技巧,提供风格化词库与参数建议,助您优化AI绘画生成效果。
- 27次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go net.Conn 写入超时为何仍会卡住:SetWriteDeadline、部分写入与连接复用检查
- 2026-08-30 501浏览
-
- Go 问答:httptrace.ClientTrace GotConnInfo 怎么判断连接是否复用:连接池与请求时序边界
- 2026-08-28 501浏览
-
- Go netip.Prefix.Contains 判断网段为什么出错:地址族、掩码长度与规范化
- 2026-08-27 501浏览

