Skip to content

Commit b5408a5

Browse files
committed
Implement GetString and GetInt functions with fallback values
1 parent 3c518a3 commit b5408a5

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

goenv.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package goenv
33
import (
44
"os"
55
"path/filepath"
6+
"strconv"
67
"strings"
78
)
89

@@ -74,3 +75,28 @@ func Load() error {
7475

7576
return nil
7677
}
78+
79+
// GetString returns the value of an environment variable if it exists; otherwise, it returns the fallback value.
80+
func GetString(key, fallback string) string {
81+
val, ok := os.LookupEnv(key)
82+
if !ok {
83+
return fallback
84+
}
85+
86+
return val
87+
}
88+
89+
// GetInt returns the integer value of an environment variable if it exists; otherwise, it returns the fallback value.
90+
func GetInt(key string, fallback int) int {
91+
val, ok := os.LookupEnv(key)
92+
if !ok {
93+
return fallback
94+
}
95+
96+
intVal, err := strconv.Atoi(val)
97+
if err != nil {
98+
return fallback
99+
}
100+
101+
return intVal
102+
}

goenv_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,46 @@ func Test_Load(t *testing.T) {
4444
t.Fatalf("Failed to load env variables: %v", err)
4545
}
4646
}
47+
48+
// Test_GetString verifies that GetString correctly retrieves environment variables and falls back when necessary.
49+
func Test_GetString(t *testing.T) {
50+
key := "TEST_STRING"
51+
value := "hello"
52+
fallback := "default"
53+
54+
os.Setenv(key, value)
55+
defer os.Unsetenv(key)
56+
57+
if got := GetString(key, fallback); got != value {
58+
t.Errorf("GetString(%q, %q) = %q; want %q", key, fallback, got, value)
59+
}
60+
61+
os.Unsetenv(key)
62+
if got := GetString(key, fallback); got != fallback {
63+
t.Errorf("GetString(%q, %q) = %q; want %q", key, fallback, got, fallback)
64+
}
65+
}
66+
67+
// Test_GetInt verifies that GetInt correctly retrieves integer environment variables and falls back when necessary.
68+
func Test_GetInt(t *testing.T) {
69+
key := "TEST_INT"
70+
value := "42"
71+
fallback := 10
72+
73+
os.Setenv(key, value)
74+
defer os.Unsetenv(key)
75+
76+
if got := GetInt(key, fallback); got != 42 {
77+
t.Errorf("GetInt(%q, %d) = %d; want %d", key, fallback, got, 42)
78+
}
79+
80+
os.Setenv(key, "invalid")
81+
if got := GetInt(key, fallback); got != fallback {
82+
t.Errorf("GetInt(%q, %d) with invalid value = %d; want %d", key, fallback, got, fallback)
83+
}
84+
85+
os.Unsetenv(key)
86+
if got := GetInt(key, fallback); got != fallback {
87+
t.Errorf("GetInt(%q, %d) = %d; want %d", key, fallback, got, fallback)
88+
}
89+
}

0 commit comments

Comments
 (0)