Skip to content

Commit 8e384c4

Browse files
committed
fix: solved error on Protobuf messages with oneof fields
1 parent 9775f1c commit 8e384c4

3 files changed

Lines changed: 19 additions & 18 deletions

File tree

mapper/constants.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const (
77
UnknownFields = "unknownFields"
88
ProtobufTag = "protobuf"
99
ProtobufOneOf = "oneof"
10+
ProtobufOneOfTag = "protobuf_oneof"
1011
ProtobufNamePrefix = "name="
1112
JSONTag = "json"
1213
JSONOmitempty = "omitempty"

mapper/protobuf.go

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ func (p ProtobufGenerator) NewMapper(structInstance any) (
7373
if IsProtobufGeneratedField(fieldName) {
7474
continue
7575
}
76+
77+
// Omit protobuf oneof field (optional fields)
78+
if IsProtobufOneOfField(structField) {
79+
continue
80+
}
7681

7782
// Get the Protobuf tag of the field
7883
protobufTag, err := GetProtobufTag(structField, fieldName)
@@ -124,23 +129,6 @@ func (p ProtobufGenerator) NewMapper(structInstance any) (
124129
rootMapper.AddFieldNestedMapper(fieldName, fieldNestedMapper)
125130
}
126131

127-
// Check if the field is an interface (special case for oneof fields)
128-
if fieldType.Kind() == reflect.Interface {
129-
// Set field as not required
130-
rootMapper.SetFieldIsRequired(fieldName, false)
131-
132-
// Print field
133-
DetectedField(
134-
structTypeName,
135-
fieldName,
136-
fieldType,
137-
protobufTag,
138-
false,
139-
p.logger,
140-
)
141-
continue
142-
}
143-
144132
// Set field as required
145133
rootMapper.SetFieldIsRequired(fieldName, true)
146134

mapper/utils.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,26 @@ func GetJSONTagName(jsonTag, fieldName string) (string, error) {
5151
// - string: Protobuf tag
5252
// - error: error if the Protobuf tag is not found
5353
func GetProtobufTag(structField reflect.StructField, fieldName string) (string, error) {
54-
// Get the Protobuf tag of the field
5554
protobufTag := structField.Tag.Get(ProtobufTag)
5655
if protobufTag == "" {
5756
return "", fmt.Errorf(ErrProtobufTagNotFound, fieldName)
5857
}
5958
return protobufTag, nil
6059
}
6160

61+
// IsProtobufOneOfField checks if the struct field is a Protobuf oneof field
62+
//
63+
// Parameters:
64+
//
65+
// - structField: The struct field
66+
//
67+
// Returns:
68+
//
69+
// - bool: true if the struct field is a Protobuf oneof field
70+
func IsProtobufOneOfField(structField reflect.StructField) bool {
71+
return structField.Tag.Get(ProtobufOneOfTag) != ""
72+
}
73+
6274
// GetProtobufTagName returns the Protobuf tag name for a given struct field name
6375
//
6476
// Parameters:

0 commit comments

Comments
 (0)