diff --git a/bench_test.go b/bench_test.go index 8bc2fd3..82767ef 100644 --- a/bench_test.go +++ b/bench_test.go @@ -190,3 +190,10 @@ func BenchmarkFileExistsMissing(b *testing.B) { FileExists("missing.go") } } + +func BenchmarkGetDefaultFromEnv(b *testing.B) { + b.Setenv("test", "value") + for i := 0; i < b.N; i++ { + GetDefaultFromEnv("test", "default") + } +} diff --git a/generate.go b/generate.go index 5f0e2e7..60d791c 100644 --- a/generate.go +++ b/generate.go @@ -7,11 +7,11 @@ import ( ) // GenerateRandInt securely generate a random int64. The input is the maximum value that the random int can be. -func GenerateRandInt(x int) (returnValue int, returnError error) { - if x <= 0 { +func GenerateRandInt(max int) (returnValue int, returnError error) { + if max <= 0 { return 0, errors.New("need a row amount of greater than 0") } - value, returnError := rand.Int(rand.Reader, big.NewInt(int64(x))) + value, returnError := rand.Int(rand.Reader, big.NewInt(int64(max))) returnValue = int(value.Int64()) return } diff --git a/parse.go b/parse.go index 311beda..b723fc2 100644 --- a/parse.go +++ b/parse.go @@ -141,3 +141,11 @@ func FileExists(filename string) bool { } return true } + +// GetDefaultFromEnv checks if the key exists in the environment variables. If yes then returns that value and if not returns default value. +func GetDefaultFromEnv(key, fallback string) string { + if value, ok := os.LookupEnv(key); ok { + return value + } + return fallback +} diff --git a/parse_test.go b/parse_test.go index 6d75fcc..3222789 100644 --- a/parse_test.go +++ b/parse_test.go @@ -122,7 +122,7 @@ func TestIntSearch(t *testing.T) { } func TestGetEnv(t *testing.T) { - expectedValue := "value" + const expectedValue = "value" t.Setenv("test", expectedValue) returnValue := GetEnv("test", "") if returnValue != expectedValue { @@ -216,3 +216,15 @@ func TestFileExists(t *testing.T) { } os.Remove("test") } + +func TestGetDefaultFromEnv(t *testing.T) { + t.Setenv("test", "value") + result := GetDefaultFromEnv("test", "default") + if result != "value" { + t.Errorf("Wanted 'value' and got %s", result) + } + result = GetDefaultFromEnv("missing", "default") + if result != "default" { + t.Errorf("Wanted 'default' and got %s", result) + } +}