Skip to content

Commit

Permalink
fix: Use default value for empty env vars (#7297)
Browse files Browse the repository at this point in the history
Signed-off-by: Simon Behar <simbeh7@gmail.com>
  • Loading branch information
simster7 authored and sarabala1979 committed Dec 15, 2021
1 parent 2f96c46 commit 06e5950
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 3 additions & 3 deletions util/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func LookupEnvDurationOr(key string, o time.Duration) time.Duration {
v, found := os.LookupEnv(key)
if found {
if found && v != "" {
d, err := time.ParseDuration(v)
if err != nil {
log.WithField(key, v).WithError(err).Panic("failed to parse")
Expand All @@ -23,7 +23,7 @@ func LookupEnvDurationOr(key string, o time.Duration) time.Duration {

func LookupEnvIntOr(key string, o int) int {
v, found := os.LookupEnv(key)
if found {
if found && v != "" {
d, err := strconv.Atoi(v)
if err != nil {
log.WithField(key, v).WithError(err).Panic("failed to convert to int")
Expand All @@ -36,7 +36,7 @@ func LookupEnvIntOr(key string, o int) int {

func LookupEnvFloatOr(key string, o float64) float64 {
v, found := os.LookupEnv(key)
if found {
if found && v != "" {
d, err := strconv.ParseFloat(v, 64)
if err != nil {
log.WithField(key, v).WithError(err).Panic("failed to convert to float")
Expand Down
6 changes: 6 additions & 0 deletions util/env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ func TestLookupEnvDurationOr(t *testing.T) {
assert.Panics(t, func() { LookupEnvDurationOr("FOO", time.Second) }, "bad value")
_ = os.Setenv("FOO", "1h")
assert.Equal(t, time.Hour, LookupEnvDurationOr("FOO", time.Second), "env var value")
_ = os.Setenv("FOO", "")
assert.Equal(t, time.Second, LookupEnvDurationOr("FOO", time.Second), "empty var value; default value")
}

func TestLookupEnvIntOr(t *testing.T) {
Expand All @@ -24,6 +26,8 @@ func TestLookupEnvIntOr(t *testing.T) {
assert.Panics(t, func() { LookupEnvIntOr("FOO", 1) }, "bad value")
_ = os.Setenv("FOO", "2")
assert.Equal(t, 2, LookupEnvIntOr("FOO", 1), "env var value")
_ = os.Setenv("FOO", "")
assert.Equal(t, 1, LookupEnvIntOr("FOO", 1), "empty var value; default value")
}

func TestLookupEnvFloatOr(t *testing.T) {
Expand All @@ -33,4 +37,6 @@ func TestLookupEnvFloatOr(t *testing.T) {
assert.Panics(t, func() { LookupEnvFloatOr("FOO", 1.) }, "bad value")
_ = os.Setenv("FOO", "2.0")
assert.Equal(t, 2., LookupEnvFloatOr("FOO", 1.), "env var value")
_ = os.Setenv("FOO", "")
assert.Equal(t, 1., LookupEnvFloatOr("FOO", 1.), "empty var value; default value")
}

0 comments on commit 06e5950

Please sign in to comment.