This commit is contained in:
Étienne BERSAC 2024-05-08 11:26:18 +07:00 committed by GitHub
commit 2411ee6f63
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 26 additions and 3 deletions

View file

@ -199,6 +199,7 @@ type Viper struct {
configType string
configPermissions os.FileMode
envPrefix string
envPrefixStrict bool
// Specific commands for ini parsing
iniLoadOptions ini.LoadOptions
@ -284,6 +285,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()
@ -521,19 +531,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)
@ -964,6 +979,7 @@ func (v *Viper) Sub(key string) *Viper {
subv.parents = append(subv.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

View file

@ -682,6 +682,13 @@ func TestEnvPrefix(t *testing.T) {
assert.Equal(t, "crunk", v.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) {
v := New()