From d77e7a7fbf29fc1658774bdea46676c997def41c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Fri, 4 Jan 2019 23:17:38 +0100 Subject: [PATCH] Add string replacer interface --- README.md | 6 +++--- viper.go | 14 ++++++++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0208eac..63b7f3c 100644 --- a/README.md +++ b/README.md @@ -185,8 +185,8 @@ with ENV: * `AutomaticEnv()` * `BindEnv(string...) : error` * `SetEnvPrefix(string)` - * `SetEnvKeyReplacer(string...) *strings.Replacer` - * `AllowEmptyEnvVar(bool)` + * `SetEnvKeyReplacer(StringReplacer)` + * `AllowEmptyEnvVar(bool)` _When working with ENV variables, it’s important to recognize that Viper treats ENV variables as case sensitive._ @@ -213,7 +213,7 @@ time a `viper.Get` request is made. It will apply the following rules. It will check for a environment variable with a name matching the key uppercased and prefixed with the `EnvPrefix` if set. -`SetEnvKeyReplacer` allows you to use a `strings.Replacer` object to rewrite Env +`SetEnvKeyReplacer` allows you to use a `StringReplacer` object to rewrite Env 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`. diff --git a/viper.go b/viper.go index cee37b2..caa9609 100644 --- a/viper.go +++ b/viper.go @@ -131,6 +131,12 @@ func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption { } } +// 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 +} + // Viper is a prioritized configuration registry. It // maintains a set of configuration sources, fetches // values to populate those, and provides them according @@ -186,7 +192,7 @@ type Viper struct { envPrefix string automaticEnvApplied bool - envKeyReplacer *strings.Replacer + envKeyReplacer StringReplacer allowEmptyEnv bool config map[string]interface{} @@ -1095,11 +1101,11 @@ func (v *Viper) AutomaticEnv() { v.automaticEnvApplied = true } -// SetEnvKeyReplacer sets the strings.Replacer on the viper object +// SetEnvKeyReplacer sets the StringReplacer on the viper object // Useful for mapping an environmental variable to a key that does // not match it. -func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) } -func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) { +func SetEnvKeyReplacer(r StringReplacer) { v.SetEnvKeyReplacer(r) } +func (v *Viper) SetEnvKeyReplacer(r StringReplacer) { v.envKeyReplacer = r }