Lookup environment variables instead of checking if the value is empty

Empty environment variables are perfectly valid values.
Fortunately Go provides a way to check whether an env var
is empty or not set.

Fixes #317
This commit is contained in:
Márk Sági-Kazár 2017-12-22 02:13:52 +01:00
parent 1a0c4a370c
commit dc3e53cb8b
No known key found for this signature in database
GPG Key ID: 34CC109EB5ED1C2A
1 changed files with 5 additions and 6 deletions

View File

@ -337,11 +337,11 @@ func (v *Viper) mergeWithEnvPrefix(in string) string {
// getEnv is a wrapper around os.Getenv which replaces characters in the original // getEnv is a wrapper around os.Getenv which replaces characters in the original
// key. This allows env vars which have different keys than the config object // key. This allows env vars which have different keys than the config object
// keys. // keys.
func (v *Viper) getEnv(key string) string { func (v *Viper) getEnv(key string) (string, bool) {
if v.envKeyReplacer != nil { if v.envKeyReplacer != nil {
key = v.envKeyReplacer.Replace(key) key = v.envKeyReplacer.Replace(key)
} }
return os.Getenv(key) return os.LookupEnv(key)
} }
// ConfigFileUsed returns the file used to populate the config registry. // ConfigFileUsed returns the file used to populate the config registry.
@ -568,10 +568,9 @@ func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
// "foo.bar.baz" in a lower-priority map // "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInAutoEnv(path []string) string { func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
var parentKey string var parentKey string
var val string
for i := 1; i < len(path); i++ { for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim) parentKey = strings.Join(path[0:i], v.keyDelim)
if val = v.getEnv(v.mergeWithEnvPrefix(parentKey)); val != "" { if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
return parentKey return parentKey
} }
} }
@ -934,7 +933,7 @@ func (v *Viper) find(lcaseKey string) interface{} {
if v.automaticEnvApplied { if v.automaticEnvApplied {
// even if it hasn't been registered, if automaticEnv is used, // even if it hasn't been registered, if automaticEnv is used,
// check any Get request // check any Get request
if val = v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); val != "" { if val, ok := v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); ok {
return val return val
} }
if nested && v.isPathShadowedInAutoEnv(path) != "" { if nested && v.isPathShadowedInAutoEnv(path) != "" {
@ -943,7 +942,7 @@ func (v *Viper) find(lcaseKey string) interface{} {
} }
envkey, exists := v.env[lcaseKey] envkey, exists := v.env[lcaseKey]
if exists { if exists {
if val = v.getEnv(envkey); val != "" { if val, ok := v.getEnv(envkey); ok {
return val return val
} }
} }