mirror of
https://github.com/spf13/viper
synced 2025-05-07 20:57:18 +00:00
added allowEmptyMap option
This commit is contained in:
parent
f1d2c470bf
commit
a593aea01d
2 changed files with 30 additions and 0 deletions
18
viper.go
18
viper.go
|
@ -205,6 +205,7 @@ type Viper struct {
|
|||
automaticEnvApplied bool
|
||||
envKeyReplacer StringReplacer
|
||||
allowEmptyEnv bool
|
||||
allowEmptyMap bool
|
||||
|
||||
config map[string]interface{}
|
||||
override map[string]interface{}
|
||||
|
@ -526,6 +527,15 @@ func (v *Viper) mergeWithEnvPrefix(in string) string {
|
|||
return strings.ToUpper(in)
|
||||
}
|
||||
|
||||
// AllowEmptyMap tells Viper to consider set,
|
||||
// but empty maps as valid values instead of falling back.
|
||||
// For backward compatibility reasons this is false by default.
|
||||
func AllowEmptyMap(allowEmptyMap bool) { v.AllowEmptyMap(allowEmptyMap) }
|
||||
|
||||
func (v *Viper) AllowEmptyMap(allowEmptyMap bool) {
|
||||
v.allowEmptyMap = allowEmptyMap
|
||||
}
|
||||
|
||||
// AllowEmptyEnv tells Viper to consider set,
|
||||
// but empty environment variables as valid values instead of falling back.
|
||||
// For backward compatibility reasons this is false by default.
|
||||
|
@ -2011,6 +2021,14 @@ func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interfac
|
|||
shadow[strings.ToLower(fullKey)] = true
|
||||
continue
|
||||
}
|
||||
|
||||
if v.allowEmptyMap {
|
||||
if len(val.(map[string]interface{})) == 0 {
|
||||
shadow[strings.ToLower(fullKey)] = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// recursively merge to shadow map
|
||||
shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
|
||||
}
|
||||
|
|
|
@ -60,6 +60,8 @@ type testUnmarshalExtra struct {
|
|||
var tomlExample = []byte(`
|
||||
title = "TOML Example"
|
||||
|
||||
[empty.map]
|
||||
|
||||
[owner]
|
||||
organization = "MongoDB"
|
||||
Bio = "MongoDB Chief Developer Advocate & Hacker at Large"
|
||||
|
@ -669,6 +671,16 @@ func TestEmptyEnv_Allowed(t *testing.T) {
|
|||
assert.Equal(t, "Cake", Get("name"))
|
||||
}
|
||||
|
||||
func TestEmptyMap_Allowed(t *testing.T) {
|
||||
initTOML()
|
||||
AllowEmptyMap(true)
|
||||
|
||||
allkeys := sort.StringSlice(AllKeys())
|
||||
allkeys.Sort()
|
||||
|
||||
assert.Equal(t, sort.StringSlice(sort.StringSlice{"empty.map", "owner.bio", "owner.dob", "owner.organization", "title"}), allkeys)
|
||||
}
|
||||
|
||||
func TestEnvPrefix(t *testing.T) {
|
||||
initJSON()
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue