Home > OS >  How to retrieve FieldOption value
How to retrieve FieldOption value

Time:09-25

I have proto:

extend google.protobuf.FieldOptions {
  string foo_option = 50000;
}


message Request {
  // all fields have foo_option
  string str1 = 1 [(foo_option) = "bar1"];
  string str2 = 1 [(foo_option) = "bar2"];
}

In Go, given req *Request, how do I retrieve the values of foo_option of each field?

CodePudding user response:

From a protoreflect.FieldDescriptor, use Options() method.

You will need a few type assertions to retrieve the actual option value. The full snippet might be like this:

// imports
// "google.golang.org/protobuf/proto"
// "google.golang.org/protobuf/reflect/protoreflect"
// "google.golang.org/protobuf/types/descriptorpb"

    p := msg.ProtoReflect()
    p.Range(func(fd protoreflect.FieldDescriptor, value protoreflect.Value) bool {
        opts := fd.Options().(*descriptorpb.FieldOptions)
        s, _ := proto.GetExtension(opts, mypbpkg.E_FooOption)
        fmt.Println(*s.(*string)) // bar1
        return true
    })
  • Related