Skip to content

Commit

Permalink
Add env.Int function for retrieving integer environment variables (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
zwass committed Jan 23, 2019
1 parent f730236 commit c155a91
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
20 changes: 18 additions & 2 deletions env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package env
import (
"fmt"
"os"
"strconv"
"time"
)

Expand All @@ -29,8 +30,23 @@ func String(key, def string) string {
return def
}

// Bool returns the environment variable value specified by the key parameter,
// otherwise returning a default value if set.
// Int returns the environment variable value specified by the key parameter,
// parsed as an integer. If the environment variable is not set, the default
// value is returned. If parsing the integer fails, Int will exit the program.
func Int(key string, def int) int {
if env, ok := os.LookupEnv(key); ok {
i, err := strconv.Atoi(env)
if err != nil {
fmt.Fprintf(os.Stderr, "env: parse int from flag: %s\n", err)
os.Exit(1)
}
return i
}
return def
}

// Bool returns the environment variable value specified by the key parameter
// (parsed as a boolean), otherwise returning a default value if set.
func Bool(key string, def bool) bool {
env, ok := os.LookupEnv(key)
if !ok {
Expand Down
31 changes: 31 additions & 0 deletions env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,34 @@ func TestBool(t *testing.T) {
t.Errorf("have %v, want %v", have, want)
}
}

func TestInt(t *testing.T) {
var tests = []struct {
env string
value int
}{
{env: "1337", value: 1337},
{env: "1", value: 1},
{env: "-34", value: -34},
{env: "0", value: 0},
}

for _, tt := range tests {
t.Run(tt.env, func(t *testing.T) {
key := "TEST_INT"
if err := os.Setenv(key, tt.env); err != nil {
t.Fatalf("failed to set env var %s for test: %s\n", key, err)
}

if have, want := Int(key, 10), tt.value; have != want {
t.Errorf("have %v, want %v", have, want)
}
})
}

// test default value
def := 11
if have, want := Int("TEST_DEFAULT", def), def; have != want {
t.Errorf("have %v, want %v", have, want)
}
}

0 comments on commit c155a91

Please sign in to comment.