Skip to content

Commit

Permalink
Add MustGetEnv methods for use with numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
Eli Fabens committed Jul 12, 2019
1 parent 1d51ad9 commit 8592054
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions os.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package utils
import (
"fmt"
"os"
"strconv"
)

// MustGetenv attempts to lookup and return the value associated with the specified environment variable identifier, panic'ing if no value is associated with that identifier
Expand All @@ -14,6 +15,48 @@ func MustGetenv(env string) string {
return value
}

// MustGetenvInt attempts to lookup and return the value associated with the specified environment variable identifier and cast it to an int,
//panic'ing if no value is associated with that identifier or it cannot be cast
func MustGetenvInt(env string) int {
value := MustGetenv(env)
intVal, err := strconv.Atoi(value)
if err != nil {
panic(fmt.Sprintf("Provided Environment variable for: %v can not be cast to int: %s\n", env, value))
}
return intVal
}

// MustGetenvIntNonZero attempts to lookup and return the value associated with the specified environment variable identifier and cast it to an int,
//panic'ing if no value is associated with that identifier, if it cannot be cast, or if once cast equals zero
func MustGetenvIntNonZero(env string) int {
value := MustGetenvInt(env)
if value == 0 {
panic(fmt.Sprintf("Provided Environment variable equals 0 when explicitly not allowed: %s\n", env))
}
return value
}

// MustGetenvFloat attempts to lookup and return the value associated with the specified environment variable identifier and cast it to a float,
//panic'ing if no value is associated with that identifier or it cannot be cast
func MustGetenvFloat(env string) float64 {
value := MustGetenv(env)
floatVal, err := strconv.ParseFloat(value, 64)
if err != nil {
panic(fmt.Sprintf("Provided Environment variable for: %v can not be cast to float: %s\n", env, value))
}
return floatVal
}

// MustGetenvFloatNonZero attempts to lookup and return the value associated with the specified environment variable identifier and cast it to a float,
//panic'ing if no value is associated with that identifier, if it cannot be cast, or if once cast equals zero
func MustGetenvFloatNonZero(env string) float64 {
value := MustGetenvFloat(env)
if value == 0 {
panic(fmt.Sprintf("Provided Environment variable equals 0 when explicitly not allowed: %s\n", env))
}
return value
}

// EnvOrDefault fetches an environment variable value, or if not set returns the fallback value
func EnvOrDefault(key string, fallback string) string {
if val, ok := os.LookupEnv(key); ok {
Expand Down

0 comments on commit 8592054

Please sign in to comment.