Skip to content

Commit fb6eb1e

Browse files
krakowskisagikazarmark
authored andcommitted
fix: merge missing struct keys inside UnmarshalExact
1 parent f5fcb4a commit fb6eb1e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

viper.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -1179,7 +1179,14 @@ func (v *Viper) UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
11791179
config := defaultDecoderConfig(rawVal, opts...)
11801180
config.ErrorUnused = true
11811181

1182-
return decode(v.AllSettings(), config)
1182+
// TODO: make this optional?
1183+
structKeys, err := v.decodeStructKeys(rawVal, opts...)
1184+
if err != nil {
1185+
return err
1186+
}
1187+
1188+
// TODO: struct keys should be enough?
1189+
return decode(v.getSettings(append(v.AllKeys(), structKeys...)), config)
11831190
}
11841191

11851192
// BindPFlags binds a full flag set to the configuration, using each flag's long

viper_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -1052,6 +1052,32 @@ func TestUnmarshalWithAutomaticEnv(t *testing.T) {
10521052

10531053
assert.Error(t, err, "expected viper.Unmarshal to return error due to unset field 'FLAG'")
10541054
})
1055+
1056+
t.Run("Exact", func(t *testing.T) {
1057+
var config Configuration
1058+
1059+
v.Set("port", 1234)
1060+
if err := v.UnmarshalExact(&config); err != nil {
1061+
t.Fatalf("unable to decode into struct, %v", err)
1062+
}
1063+
1064+
assert.Equal(
1065+
t,
1066+
Configuration{
1067+
Name: "Steve",
1068+
Port: 1234,
1069+
Duration: time.Second + time.Millisecond,
1070+
Modes: []int{1, 2, 3},
1071+
Authentication: AuthConfig{
1072+
Secret: "42",
1073+
},
1074+
Storage: StorageConfig{
1075+
Size: 4096,
1076+
},
1077+
},
1078+
config,
1079+
)
1080+
})
10551081
}
10561082

10571083
func TestBindPFlags(t *testing.T) {

0 commit comments

Comments
 (0)