feat: Strict env prefix

Signed-off-by: Étienne BERSAC <etienne.bersac@dalibo.com>
This commit is contained in:
Étienne BERSAC 2023-09-12 10:20:20 +02:00
parent d4c2f2ef40
commit a0b31625de
No known key found for this signature in database
GPG key ID: 95997557AD5A6DBF
2 changed files with 26 additions and 3 deletions

View file

@ -197,6 +197,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
@ -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. // NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper { func NewWithOptions(opts ...Option) *Viper {
v := New() v := New()
@ -519,19 +529,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)
@ -959,6 +974,7 @@ func (v *Viper) Sub(key string) *Viper {
subv.parents = append(v.parents, strings.ToLower(key)) subv.parents = append(v.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

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