Skip to content

Commit

Permalink
Merge pull request mitchellh#7 from go-viper/fix-using-ignore-untagge…
Browse files Browse the repository at this point in the history
…d-fields

Fix untagged field decoding in case of decode to struct
  • Loading branch information
sagikazarmark committed Dec 18, 2023
2 parents 524a9c9 + 2e2be32 commit 9b573a2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions mapstructure.go
Expand Up @@ -1363,6 +1363,9 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
fieldName := field.Name

tagValue := field.Tag.Get(d.config.TagName)
if tagValue == "" && d.config.IgnoreUntaggedFields {
continue
}
tagValue = strings.SplitN(tagValue, ",", 2)[0]
if tagValue != "" {
fieldName = tagValue
Expand Down
38 changes: 38 additions & 0 deletions mapstructure_test.go
Expand Up @@ -2735,6 +2735,44 @@ func TestDecoder_IgnoreUntaggedFields(t *testing.T) {
}
}

func TestDecoder_IgnoreUntaggedFieldsWithStruct(t *testing.T) {
type Output struct {
UntaggedInt int
TaggedNumber int `mapstructure:"tagged_number"`
UntaggedString string
TaggedString string `mapstructure:"tagged_string"`
}
input := map[interface{}]interface{}{
"untaggedint": 31,
"tagged_number": 41,
"untagged_string": "hidden",
"tagged_string": "visible",
}
actual := Output{}
config := &DecoderConfig{
Result: &actual,
IgnoreUntaggedFields: true,
}

decoder, err := NewDecoder(config)
if err != nil {
t.Fatalf("err: %s", err)
}

err = decoder.Decode(input)
if err != nil {
t.Fatalf("err: %s", err)
}

expected := Output{
TaggedNumber: 41,
TaggedString: "visible",
}
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Decode() expected: %#v\ngot: %#v", expected, actual)
}
}

func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
var result Slice
err := Decode(input, &result)
Expand Down

0 comments on commit 9b573a2

Please sign in to comment.