protobuf-go icon indicating copy to clipboard operation
protobuf-go copied to clipboard

feat: make it so you can optionally have DiscardUnknown not apply to enums

Open djgilcrease opened this issue 6 months ago • 1 comments

https://github.com/protocolbuffers/protobuf-go/commit/70db1e1de28451dbcc3877e388fda2fbb9e04e00#diff-4bfd19b0e2b567c0f35f87a774a43846bc5b549661d952fb1177867cd762e6ba made it so DiscardUnknown also applied to enum values following the discussion https://github.com/golang/protobuf/issues/1208 to comply with the C++ behavior.

The comment by https://github.com/golang/protobuf/issues/1208#issuecomment-698837670 directly applies to my situation in that for historical reasons we had AllowUnknownFields set to true in the old jsonpb code. This did not affect ENUMS and allowed our service to properly throw a 400 error for invalid ENUM values (yes I know we do not follow best practice of having the zero value be invalid). In the migration to this code we still need DiscardUnknown to be true, but also retain the behavior of validating enum fields.

To achieve this I added ErrorOnUnknownEnumValue to UnmarshalOptions that will still let DiscardUnknown apply to field names, but NOT ENUM values. This change will have no affect if DiscardUnknown is set to false and no affect on any other field type except enums. I also made the default value of ErrorOnUnknownEnumValue retain current behavior if DiscardUnknown is set to true.

djgilcrease avatar Aug 13 '24 16:08 djgilcrease