fix: Unmarshal struct decoding when passing in a pointer to a pointer

Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com>
This commit is contained in:
Mark Sagi-Kazar 2023-12-08 18:59:35 +01:00
parent 9154b900c3
commit ca55de9785
No known key found for this signature in database
GPG key ID: 31AB0439F4C5C90E
2 changed files with 49 additions and 0 deletions

View file

@ -1127,6 +1127,13 @@ func (v *Viper) Unmarshal(rawVal any, opts ...DecoderConfigOption) error {
func (v *Viper) decodeStructKeys(input any, opts ...DecoderConfigOption) ([]string, error) {
var structKeyMap map[string]any
rv := reflect.ValueOf(input)
for rv.Kind() == reflect.Ptr {
rv = reflect.Indirect(rv)
}
input = rv.Interface()
err := decode(input, defaultDecoderConfig(&structKeyMap, opts...))
if err != nil {
return nil, err

View file

@ -1080,6 +1080,48 @@ func TestUnmarshalWithAutomaticEnv(t *testing.T) {
})
}
func TestUnmarshalIndirection(t *testing.T) {
v := New()
v.Set("foo", "bar")
type config struct {
Foo string
}
var C config
CC := &C
CCC := &CC
err := v.Unmarshal(&CCC)
require.NoError(t, err)
assert.Equal(t, config{"bar"}, C)
}
func TestUnmarshalInterface(t *testing.T) {
v := New()
v.Set("foo", "bar")
type someInterface interface {
Foo() string
}
type config struct {
Foo string
Fooer someInterface
}
var C config
err := v.Unmarshal(&C)
require.NoError(t, err)
assert.Equal(t, config{Foo: "bar"}, C)
}
func TestBindPFlags(t *testing.T) {
v := New() // create independent Viper object
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)