首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Protobuf自定义选项在protojson库生成的JSON中没有显示

Protobuf自定义选项在protojson库生成的JSON中没有显示
EN

Stack Overflow用户
提问于 2020-12-08 08:46:54
回答 1查看 1.2K关注 0票数 0

我试图从Protobuf编译器生成的中提取Protobuf自定义选项。我不能用原型反射来完成这个任务。因此,我试图使用protojson库来实现这个目标。

PS :导入Go生成的代码不是我的用例的一个选项。

下面是我正在测试的Protobuf消息:

代码语言:javascript
复制
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

以下是我的成就:

代码语言:javascript
复制
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

代码语言:javascript
复制
{
  "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"
}

因此,有关我的自定义选项的数据显示在扩展中。但是我真正想要的是那些自定义选项在“选项”中的价值。(我的例子是(食物)=“奶酪”,我想要奶酪)

可以告诉我如何使用Protojson或Protojson.从FileDescriptorSet中提取自定义选项。

我试了很多次尝试使用Protoreflect来提取它,但是失败了!

EN

回答 1

Stack Overflow用户

发布于 2020-12-28 03:10:22

虽然对于如何在生成的JSON中获取自定义选项不是一个具体的答案,但我相信我已经回答了您的基本问题:如何在不加载生成的Go代码的情况下访问自定义选项。这要感谢dsnet对我在高朗发行板上的问题的回答。不用说,这一棘手解决办法的所有功劳都归功于他。这篇文章的重点是使用一个运行时填充的protoregistry.Types (实际上知道定制选项)来管理这些选项,然后解封这些选项。

我对这种使用在这次回购中的方法做了一个完整的演示,关键部分(所有的核心都来自于dsnet的示例)在这里:

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65195766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档