当前位置:首页 > 文章列表 > 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推荐
  • AI Make Song:零门槛AI音乐创作平台,助你轻松制作个性化音乐
    AI Make Song
    AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
    12次使用
  • SongGenerator.io:零门槛AI音乐生成器,快速创作高质量音乐
    SongGenerator
    探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
    11次使用
  •  BeArt AI换脸:免费在线工具,轻松实现照片、视频、GIF换脸
    BeArt AI换脸
    探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
    10次使用
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    16次使用
  • Brev AI:零注册门槛的全功能免费AI音乐创作平台
    Brev AI
    探索Brev AI,一个无需注册即可免费使用的AI音乐创作平台,提供多功能工具如音乐生成、去人声、歌词创作等,适用于内容创作、商业配乐和个人创作,满足您的音乐需求。
    16次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码