diff --git a/viper.go b/viper.go index 6c9f0e0f2..a1f9d80b1 100644 --- a/viper.go +++ b/viper.go @@ -197,6 +197,7 @@ type Viper struct { configType string configPermissions os.FileMode envPrefix string + envPrefixStrict bool // Specific commands for ini parsing iniLoadOptions ini.LoadOptions @@ -282,6 +283,15 @@ func EnvKeyReplacer(r StringReplacer) Option { }) } +func StrictEnvPrefix(in string) Option { + return optionFunc(func(v *Viper) { + if "" != in { + v.envPrefix = in + v.envPrefixStrict = true + } + }) +} + // NewWithOptions creates a new Viper instance. func NewWithOptions(opts ...Option) *Viper { v := New() @@ -519,19 +529,24 @@ func SetEnvPrefix(in string) { v.SetEnvPrefix(in) } func (v *Viper) SetEnvPrefix(in string) { if in != "" { - v.envPrefix = in + v.envPrefix = in + "_" } } func GetEnvPrefix() string { return v.GetEnvPrefix() } func (v *Viper) GetEnvPrefix() string { - return v.envPrefix + p := v.envPrefix + if v.envPrefixStrict && "" != p { + // Removes automatic trailing underscore. + p = p[:len(p)-1] + } + return p } func (v *Viper) mergeWithEnvPrefix(in string) string { if v.envPrefix != "" { - return strings.ToUpper(v.envPrefix + "_" + in) + return strings.ToUpper(v.envPrefix + in) } return strings.ToUpper(in) @@ -959,6 +974,7 @@ func (v *Viper) Sub(key string) *Viper { subv.parents = append(v.parents, strings.ToLower(key)) subv.automaticEnvApplied = v.automaticEnvApplied subv.envPrefix = v.envPrefix + subv.envPrefixStrict = v.envPrefixStrict subv.envKeyReplacer = v.envKeyReplacer subv.config = cast.ToStringMap(data) return subv diff --git a/viper_test.go b/viper_test.go index ccc92250d..897cce17d 100644 --- a/viper_test.go +++ b/viper_test.go @@ -690,6 +690,13 @@ func TestEnvPrefix(t *testing.T) { assert.Equal(t, "crunk", Get("name")) } +func TestEnvPrefixStrict(t *testing.T) { + v := NewWithOptions(StrictEnvPrefix("foo")) + v.BindEnv("id") + t.Setenv("FOOID", "ok") + assert.Equal(t, "ok", v.Get("id")) +} + func TestAutoEnv(t *testing.T) { Reset()