'How to access proto.EnumValueOptions extension values

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...



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 waldenlaker
Solution 2 Robert Tiganetea