From 2e2be325602c72c20b5c3f6ef3c61232db256b15 Mon Sep 17 00:00:00 2001 From: "Anton N. Ryabkov" Date: Thu, 9 Jun 2022 14:03:40 +0700 Subject: [PATCH] Fix untagged field decoding in case of decode to struct --- mapstructure.go | 3 +++ mapstructure_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/mapstructure.go b/mapstructure.go index 7581806a..f4b1893c 100644 --- a/mapstructure.go +++ b/mapstructure.go @@ -1358,6 +1358,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 diff --git a/mapstructure_test.go b/mapstructure_test.go index d31129d7..6574c8cb 100644 --- a/mapstructure_test.go +++ b/mapstructure_test.go @@ -2732,6 +2732,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)