go - 获取 golang 的协议缓冲区选项信息
问题描述
Protocol Buffer 定义如下,TestMessage
有两个选项msg_option_a
和msg_option_b
:
syntax = "proto3";
package grpctest;
option go_package = "pb";
import "google/protobuf/descriptor.proto";
extend google.protobuf.MessageOptions {
int32 msg_option_a = 50011;
int32 msg_option_b = 50012;
}
message TestMessage {
option (msg_option_a) = 22;
option (msg_option_b) = 33;
string name = 1;
}
我想阅读两个选项的定义值:
var msg *pb.TestMessage
_, md := descriptor.ForMessage(msg)
options := md.GetOptions()
fmt.Println(options.String()) // --> [grpcapi.msg_option_a]:22 [grpcapi.msg_option_b]:33
fmt.Println(len(options.GetUninterpretedOption())) // --> 0
它可以在打印整个时获取所有选项信息MessageOptions
,GetUninterpretedOption()
返回一个选项定义数组,但它的长度为零。
以下是 type 的注释UninterpretedOption
,但我无法理解它的含义,也没有找到任何有关的信息DescriptorPool
:
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
我想得到一个具体的期权价值,但现在没有想法。
请帮忙!谢谢!
解决方案
使用proto.GetExtension
获取选项值:
var msg *pb.TestMessage
_, md := descriptor.ForMessage(msg)
options := md.GetOptions()
fmt.Println(options.String()) // --> [grpcapi.msg_option_a]:22 [grpcapi.msg_option_b]:33
fmt.Println(len(options.GetUninterpretedOption())) // --> 0
a, _ := proto.GetExtension(options, pb.E_MsgOptionA)
fmt.Println(*a.(*int32)) // --> 22
b, _ := proto.GetExtension(options, pb.E_MsgOptionB)
fmt.Println(*b.(*int32)) // --> 33
推荐阅读
- c - 如何在 c 中使用 bsearch 在结构中搜索数组
- python-3.x - Python如何区分参数是否为默认参数?
- reactjs - 切换组件不更新视图
- c# - 将资源添加到 Xamarin.Forms NuGet
- r - 为什么在批量调用中将路径写入我的ui
- php - 如何通过 PHP 中的 URL 更新数据库中的数据
- flutter - 升级到 Android X 后的 Firebase 问题
- ruby-on-rails - 如何让 ActiveRecord 在原始语句中绑定?
- c# - 由于文件格式或文件扩展名无效而无法打开文件的 C# Web API 导出 excel 文件的问题
- algorithm - 如何使用powershell从文件夹>子文件夹打印文件