Add string replacer interface and env key replacer option

This commit is contained in:
Mark Sagi-Kazar 2019-12-06 14:11:31 +01:00 committed by Márk Sági-Kazár
parent 6fcf985c5a
commit 4ad4c8df70
3 changed files with 26 additions and 1 deletions

View file

@ -263,6 +263,9 @@ keys to an extent. This is useful if you want to use `-` or something in your
`Get()` calls, but want your environmental variables to use `_` delimiters. An
example of using it can be found in `viper_test.go`.
Alternatively, you can use `EnvKeyReplacer` with `NewWithOptions` factory function.
Unlike `SetEnvKeyReplacer`, it accepts a `StringReplacer` interface allowing you to write custom string replacing logic.
By default empty environment variables are considered unset and will fall back to
the next configuration source. To treat empty environment variables as set, use
the `AllowEmptyEnv` method.

View file

@ -197,7 +197,7 @@ type Viper struct {
envPrefix string
automaticEnvApplied bool
envKeyReplacer *strings.Replacer
envKeyReplacer StringReplacer
allowEmptyEnv bool
config map[string]interface{}
@ -257,6 +257,19 @@ func KeyDelimiter(d string) Option {
})
}
// StringReplacer applies a set of replacements to a string.
type StringReplacer interface {
// Replace returns a copy of s with all replacements performed.
Replace(s string) string
}
// EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys.
func EnvKeyReplacer(r StringReplacer) Option {
return optionFunc(func(v *Viper) {
v.envKeyReplacer = r
})
}
// NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper {
v := New()

View file

@ -549,6 +549,15 @@ func TestSetEnvKeyReplacer(t *testing.T) {
assert.Equal(t, "30s", Get("refresh-interval"))
}
func TestEnvKeyReplacer(t *testing.T) {
v := NewWithOptions(EnvKeyReplacer(strings.NewReplacer("-", "_")))
v.AutomaticEnv()
_ = os.Setenv("REFRESH_INTERVAL", "30s")
assert.Equal(t, "30s", v.Get("refresh-interval"))
}
func TestAllKeys(t *testing.T) {
initConfigs()