golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.66k stars 1.58k forks source link

custom options doesn't seem to work for protobuf map fields #1624

Open yangzh opened 2 weeks ago

yangzh commented 2 weeks ago

What version of protobuf and what language are you using? The latest release of Go package of "google.golang.org/protobuf/proto" and related packages

What did you do? I was trying to use custom options to augment behavior, and this doesn't seem to work for map fields.

For example, in my .proto file: ` enum Hint { HINT_UNKNOWN = 0; HINT_RED = 1; HINT_BLUE = 2; }

message SomeMessage { map<uint32, string> attrs = 1 [(hint)=HINT_RED]; } `

I would expect to retrieve the value of the custom_settings with the following code:

hint := proto.GetExtension(fd.Options(), E_Hint).(Hint) where fd is the protoreflect.FieldDescriptor for the field. This works fine for regular non-map fields (either scalar or message field), but doesn't seem to work for maps.

and I tried to use fd or fd.MapKey() or fd.MapValue(), but still no luck there.

What did you expect to see? Retrieve the expected custom options, in above case, HINT_RED.

What did you see instead? HINT_UNKNOWN

Make sure you include information that can help us debug (full error message, exception listing, stack trace, logs).

Anything else we should know about your project / environment?

neild commented 2 weeks ago

Works for me. Can you provide the complete .proto file and complete Go code?

func Test(t *testing.T) {
        m := &testoptspb.TestMessageWithCustomOptions{}
        md := m.ProtoReflect().Descriptor()
        fd := md.Fields().ByName("map_field")
        v := proto.GetExtension(fd.Options(), testoptspb.E_FieldOpt1).(uint64)
        if v != 12345 {
                t.Errorf("v = %v, want 12345", v)
        }
}

(Using https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/unittest_custom_options.proto)

aktau commented 1 week ago

@yangzh were you able to try again with the approach that @neild posted? If so can you comment or close the issue?