diff --git a/README.md b/README.md index a574677..30f72ad 100644 --- a/README.md +++ b/README.md @@ -507,6 +507,7 @@ The following functions and methods exist: * `GetInt(key string) : int` * `GetIntSlice(key string) : []int` * `GetString(key string) : string` + * `GetStringPtr(key string) : *string` * `GetStringMap(key string) : map[string]interface{}` * `GetStringMapString(key string) : map[string]string` * `GetStringSlice(key string) : []string` @@ -517,7 +518,7 @@ The following functions and methods exist: One important thing to recognize is that each Get function will return a zero value if it’s not found. To check if a given key exists, the `IsSet()` method -has been provided. +has been provided. `GetStringPtr()`, though, will return nil for empty string. Example: ```go diff --git a/viper.go b/viper.go index a8f84b5..ae0d1fe 100644 --- a/viper.go +++ b/viper.go @@ -793,6 +793,16 @@ func (v *Viper) GetString(key string) string { return cast.ToString(v.Get(key)) } +// GetStringPt returns the value associated with the key as a string pointer, nil if it's empty string. +func GetStringPtr(key string) *string { return v.GetStringPtr(key) } +func (v *Viper) GetStringPtr(key string) *string { + s := v.GetString(key) + if s == "" { + return nil + } + return &s +} + // GetBool returns the value associated with the key as a boolean. func GetBool(key string) bool { return v.GetBool(key) } func (v *Viper) GetBool(key string) bool { diff --git a/viper_test.go b/viper_test.go index f9dc34a..81175a3 100644 --- a/viper_test.go +++ b/viper_test.go @@ -2159,3 +2159,14 @@ func BenchmarkGetBoolFromMap(b *testing.B) { } } } + +func TestGetStringPtr(t *testing.T) { + v := New() + v.SetConfigType("yaml") + + /* config and defaults */ + v.ReadConfig(bytes.NewBuffer(yamlExample)) + + assert.Equal(t, "leather", *v.GetStringPtr("clothing.jacket")) + assert.Nil(t, v.GetStringPtr("motorcycle")) +}