Skip to content

Commit 9b573a2

Browse files
Merge pull request #7 from go-viper/fix-using-ignore-untagged-fields
Fix untagged field decoding in case of decode to struct
2 parents 524a9c9 + 2e2be32 commit 9b573a2

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

mapstructure.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,6 +1363,9 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
13631363
fieldName := field.Name
13641364

13651365
tagValue := field.Tag.Get(d.config.TagName)
1366+
if tagValue == "" && d.config.IgnoreUntaggedFields {
1367+
continue
1368+
}
13661369
tagValue = strings.SplitN(tagValue, ",", 2)[0]
13671370
if tagValue != "" {
13681371
fieldName = tagValue

mapstructure_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2735,6 +2735,44 @@ func TestDecoder_IgnoreUntaggedFields(t *testing.T) {
27352735
}
27362736
}
27372737

2738+
func TestDecoder_IgnoreUntaggedFieldsWithStruct(t *testing.T) {
2739+
type Output struct {
2740+
UntaggedInt int
2741+
TaggedNumber int `mapstructure:"tagged_number"`
2742+
UntaggedString string
2743+
TaggedString string `mapstructure:"tagged_string"`
2744+
}
2745+
input := map[interface{}]interface{}{
2746+
"untaggedint": 31,
2747+
"tagged_number": 41,
2748+
"untagged_string": "hidden",
2749+
"tagged_string": "visible",
2750+
}
2751+
actual := Output{}
2752+
config := &DecoderConfig{
2753+
Result: &actual,
2754+
IgnoreUntaggedFields: true,
2755+
}
2756+
2757+
decoder, err := NewDecoder(config)
2758+
if err != nil {
2759+
t.Fatalf("err: %s", err)
2760+
}
2761+
2762+
err = decoder.Decode(input)
2763+
if err != nil {
2764+
t.Fatalf("err: %s", err)
2765+
}
2766+
2767+
expected := Output{
2768+
TaggedNumber: 41,
2769+
TaggedString: "visible",
2770+
}
2771+
if !reflect.DeepEqual(expected, actual) {
2772+
t.Fatalf("Decode() expected: %#v\ngot: %#v", expected, actual)
2773+
}
2774+
}
2775+
27382776
func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
27392777
var result Slice
27402778
err := Decode(input, &result)

0 commit comments

Comments
 (0)