Reputation: 172
I have similar setup as bellow, how can I access my extension values from XYZ
enum using "github.com/golang/protobuf/proto"?
extend google.protobuf.EnumValueOptions {
Details meta = 50001;
}
message Details {
string description = 1;
}
enum MyEnum {
MY_ENUM_UNSPECIFIED = 0;
XYZ = 1 [deprecated=true, (meta) = {description: "lorem ipsum"}];
}
I'm aware of proto.GetExtension(proto.Message, proto.ExtensionDesc)
, however I wasn't able to figure out how it can be used for the enum...
Upvotes: 5
Views: 5459
Reputation: 171
Some of the methods used in current best answer is now deprecated and it is a bit lengthy.
Here is how I got it:
// pd is the module of your complied protobuf files
fd := pd.File_name_of_your_proto_file_proto
enumDesc := fd.Enums().ByName("MyEnum")
if enumDesc == nil {
panic()
}
enumValDesc := enumDesc.Values().ByName("XYZ")
if enumValDesc == nil {
panic()
}
ext := proto.GetExtension(enumValDesc.Options(), pd.E_Meta)
if enumValDesc == nil {
panic()
}
meta := ext.(*Details)
Let me know if there is a better way.
Upvotes: 6
Reputation: 21
After many hours, I have found a method to access the description for the enum. Here is my implementation, I hope it helps.
In a file called enum.go in the same package as the generated .pb file, I added this method to the enum type that retrieves the description.
func (t MyEnum) GetValue() (*Details, error) {
tt, err := proto.GetExtension(proto.MessageV1(t.Descriptor().Values().ByNumber(t.Number()).Options()), E_Details)
if err != nil {
return nil, err
}
return tt.(*Details), nil
}
I am sure there is an easier way, but until somebody finds one, this should work.
Upvotes: 2
Reputation: 7324
Bit late but I've just run into the same; you can do it like this:
fd, _ := descriptor.ForMessage(&pb.Details{})
for _, e := range fd.EnumType {
if e.GetName() == "MyEnum" {
for _, v := range e.Value {
ext, err := proto.GetExtension(v.Options, pb.E_Meta)
if err == nil {
details := ext.(*pb.Details)
// do stuff with details
}
}
}
}
There might be a more direct way of getting the enum descriptor, although I haven't managed after a bit of wrangling.
Upvotes: 3