【问题标题】:get protocol buffer option information for golang获取 golang 的协议缓冲区选项信息
【发布时间】:2018-10-17 16:59:52
【问题描述】:

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()时可以获取所有选项信息,返回选项定义数组,但长度为零。

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

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

请帮忙!谢谢!

【问题讨论】:

    标签: go protocol-buffers


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2021-12-19
      • 2011-11-15
      相关资源
      最近更新 更多