fix: avoid unmarshal panic with incorrect map keys #3002 (#3013)

master
Kevin Wan 2 years ago committed by GitHub
parent 123c61ad12
commit 4cef2b412c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -289,6 +289,10 @@ func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue any)
return reflect.ValueOf(mapValue), nil
}
if keyType != valueType.Key() {
return emptyValue, errTypeMismatch
}
refValue := reflect.ValueOf(mapValue)
targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
dereffedElemType := Deref(elemType)

@ -4437,3 +4437,18 @@ func TestFillDefaultUnmarshal(t *testing.T) {
assert.Error(t, err)
})
}
func Test_UnmarshalMap(t *testing.T) {
type Customer struct {
Names map[int]string `key:"names"`
}
input := map[string]any{
"names": map[string]any{
"19": "Tom",
},
}
var customer Customer
assert.ErrorIs(t, UnmarshalKey(input, &customer), errTypeMismatch)
}

Loading…
Cancel
Save