Added greater granularity for boolean environment variables (#511)

* Added greater granularity for boolean environment variables

* Improved solution as reviewed
This commit is contained in:
Alessandro Detta
2024-02-22 11:35:53 +01:00
committed by GitHub
parent 3d7f907a33
commit b5bed10571
7 changed files with 73 additions and 11 deletions

View File

@@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"regexp"
"slices"
"strings"
"github.com/gin-gonic/gin"
@@ -116,3 +117,13 @@ func GetQueryProps(c *gin.Context) (*QueryProps, error) {
return &qp, nil
}
func EnvAsBool(envKey string, envDef bool) bool {
validSettableValues := []string{"false", "true", "0", "1"}
envValue := os.Getenv(envKey)
if slices.Contains(validSettableValues, envValue) {
return envValue == "true" || envValue == "1"
} else {
return envDef
}
}

View File

@@ -2,6 +2,7 @@ package utils
import (
"net/http/httptest"
"os"
"testing"
"github.com/gin-gonic/gin"
@@ -106,3 +107,53 @@ func TestChartAndVersion(t *testing.T) {
})
}
}
func TestEnvAsBool(t *testing.T) {
// value: "true" | "1", default: false -> expect true
t.Setenv("TEST", "true")
want := true
if EnvAsBool("TEST", false) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
t.Setenv("TEST", "1")
want = true
if EnvAsBool("TEST", false) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
// value: "false" | "0", default: true -> expect false
t.Setenv("TEST", "false")
want = false
if EnvAsBool("TEST", true) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
t.Setenv("TEST", "0")
want = false
if EnvAsBool("TEST", true) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
// value: "" | *, default: false -> expect false
t.Setenv("TEST", "")
want = false
if EnvAsBool("TEST", false) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
t.Setenv("TEST", "10random")
want = false
if EnvAsBool("TEST", false) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
// value: "" | *, default: true -> expect true
t.Setenv("TEST", "")
want = true
if EnvAsBool("TEST", true) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
t.Setenv("TEST", "10random")
want = true
if EnvAsBool("TEST", true) != want {
t.Errorf("Env 'TEST' value '%v' should be parsed to %v", os.Getenv("TEST"), want)
}
}