Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1538,6 +1538,12 @@ func SetDefault(key string, value any) { v.SetDefault(key, value) }
// SetDefault is case-insensitive for a key.
// Default only used when no value is provided by the user via flag, config or ENV.
func (v *Viper) SetDefault(key string, value any) {
if v.defaults == nil {
v.defaults = make(map[string]any)
}
if v.keyDelim == "" {
v.keyDelim = "."
}
// If alias passed in, then set the proper default
key = v.realKey(strings.ToLower(key))
value = toCaseInsensitiveValue(value)
Expand All @@ -1561,6 +1567,12 @@ func Set(key string, value any) { v.Set(key, value) }
// Will be used instead of values obtained via
// flags, config file, ENV, default, or key/value store.
func (v *Viper) Set(key string, value any) {
if v.override == nil {
v.override = make(map[string]any)
}
if v.keyDelim == "" {
v.keyDelim = "."
}
// If alias passed in, then set the proper override
key = v.realKey(strings.ToLower(key))
value = toCaseInsensitiveValue(value)
Expand Down
16 changes: 16 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2718,3 +2718,19 @@ func skipWindows(t *testing.T) {
t.Skip("Skip test on Windows")
}
}

func TestZeroValueViperSetDefault(t *testing.T) {
v := &Viper{}
v.SetDefault("foo.bar", "baz")
if v.Get("foo.bar") != "baz" {
t.Fatalf("Expected baz, got %v", v.Get("foo.bar"))
}
}

func TestZeroValueViperSet(t *testing.T) {
v := &Viper{}
v.Set("foo.bar", "baz")
if v.Get("foo.bar") != "baz" {
t.Fatalf("Expected baz, got %v", v.Get("foo.bar"))
}
}