Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(decoder): support multiple tag names in order #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 29 additions & 10 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ type DecoderConfig struct {
// value.
Result interface{}

// The tag name that mapstructure reads for field names. This
// defaults to "mapstructure"
// The tag names that mapstructure reads for field names, separated by comma.
// First found tag will be used. This defaults to "mapstructure"
TagName string

// The option of the value in the tag that indicates a field should
Expand Down Expand Up @@ -1007,7 +1007,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
continue
}
// If "omitempty" is specified in the tag, it ignores empty values.
if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) {
if strings.Contains(tagValue[index+1:], "omitempty") && isEmptyValue(v) {
continue
}

Expand All @@ -1024,7 +1024,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
}
} else {
if strings.Index(tagValue[index+1:], "remain") != -1 {
if strings.Contains(tagValue[index+1:], "remain") {
if v.Kind() != reflect.Map {
return fmt.Errorf("error remain-tag field with invalid type: '%s'", v.Type())
}
Expand Down Expand Up @@ -1430,13 +1430,32 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
field, fieldValue := f.field, f.val
fieldName := field.Name

tagValue := field.Tag.Get(d.config.TagName)
if tagValue == "" && d.config.IgnoreUntaggedFields {
continue
// Try each tag name in order until we find a match
tagNames := strings.Split(d.config.TagName, ",")
foundTag := false
for _, tagName := range tagNames {
tagName = strings.TrimSpace(tagName)
if tagName == "" {
continue
}

tagValue := field.Tag.Get(tagName)
if tagValue == "" {
continue
}

// Found a tag value, use it
tagValue = strings.SplitN(tagValue, ",", 2)[0]
if tagValue != "" {
fieldName = tagValue
foundTag = true
break
}
}
tagValue = strings.SplitN(tagValue, ",", 2)[0]
if tagValue != "" {
fieldName = tagValue

// Skip if no tag found and ignoring untagged fields
if !foundTag && d.config.IgnoreUntaggedFields {
continue
}

rawMapKey := reflect.ValueOf(fieldName)
Expand Down