当前位置:首页 > 文章列表 > Golang > Go问答 > 自定义选项在使用 protojson 库生成的 JSON 中不可见

自定义选项在使用 protojson 库生成的 JSON 中不可见

来源:stackoverflow 2024-03-25 09:30:47 0浏览 收藏

使用 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学习网公众号了解相关技术文章。

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
如何有效地将数据库结果存储在内存缓存中如何有效地将数据库结果存储在内存缓存中
上一篇
如何有效地将数据库结果存储在内存缓存中
立即生效VSCode中文设置的方法
下一篇
立即生效VSCode中文设置的方法
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 茅茅虫AIGC检测:精准识别AI生成内容,保障学术诚信
    茅茅虫AIGC检测
    茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
    61次使用
  • 赛林匹克平台:科技赛事聚合,赋能AI、算力、量子计算创新
    赛林匹克平台(Challympics)
    探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
    84次使用
  • SEO  笔格AIPPT:AI智能PPT制作,免费生成,高效演示
    笔格AIPPT
    SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
    90次使用
  • 稿定PPT:在线AI演示设计,高效PPT制作工具
    稿定PPT
    告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
    83次使用
  • Suno苏诺中文版:AI音乐创作平台,人人都是音乐家
    Suno苏诺中文版
    探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
    85次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码