Skip to content

Commit

Permalink
Add GetDefaultFromEnv
Browse files Browse the repository at this point in the history
  • Loading branch information
Cyb3r-Jak3 committed Aug 12, 2023
1 parent 0063540 commit 2b5b5cc
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 4 deletions.
7 changes: 7 additions & 0 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
6 changes: 3 additions & 3 deletions generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
8 changes: 8 additions & 0 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
14 changes: 13 additions & 1 deletion parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 2b5b5cc

Please sign in to comment.