protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

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

Open yangzh opened this issue 1 year ago • 2 comments

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?

yangzh avatar Jul 03 '24 23:07 yangzh

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)

neild avatar Jul 04 '24 01:07 neild

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

aktau avatar Jul 09 '24 12:07 aktau