mirror of
https://github.com/spf13/viper
synced 2025-05-07 20:57:18 +00:00
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:
parent
9154b900c3
commit
ca55de9785
2 changed files with 49 additions and 0 deletions
7
viper.go
7
viper.go
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Add table
Reference in a new issue