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 configType string
configPermissions os.FileMode configPermissions os.FileMode
envPrefix string envPrefix string
envPrefixStrict bool
// Specific commands for ini parsing // Specific commands for ini parsing
iniLoadOptions ini.LoadOptions 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. // NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper { func NewWithOptions(opts ...Option) *Viper {
v := New() v := New()
@ -521,19 +531,24 @@ func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
func (v *Viper) SetEnvPrefix(in string) { func (v *Viper) SetEnvPrefix(in string) {
if in != "" { if in != "" {
v.envPrefix = in v.envPrefix = in + "_"
} }
} }
func GetEnvPrefix() string { return v.GetEnvPrefix() } func GetEnvPrefix() string { return v.GetEnvPrefix() }
func (v *Viper) GetEnvPrefix() string { 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 { func (v *Viper) mergeWithEnvPrefix(in string) string {
if v.envPrefix != "" { if v.envPrefix != "" {
return strings.ToUpper(v.envPrefix + "_" + in) return strings.ToUpper(v.envPrefix + in)
} }
return strings.ToUpper(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.parents = append(subv.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix subv.envPrefix = v.envPrefix
subv.envPrefixStrict = v.envPrefixStrict
subv.envKeyReplacer = v.envKeyReplacer subv.envKeyReplacer = v.envKeyReplacer
subv.config = cast.ToStringMap(data) subv.config = cast.ToStringMap(data)
return subv return subv

View file

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