首页 > 解决方案 > 获取 golang 的协议缓冲区选项信息

问题描述

Protocol Buffer 定义如下,TestMessage有两个选项msg_option_amsg_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

它可以在打印整个时获取所有选项信息MessageOptionsGetUninterpretedOption()返回一个选项定义数组,但它的长度为零。

以下是 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.

我想得到一个具体的期权价值,但现在没有想法。

请帮忙!谢谢!

标签: goprotocol-buffers

解决方案


使用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

推荐阅读