1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
package env
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// GetBool fetches and parses a boolean typed environment variable
//
// If the variable is empty, returns `fallback` and no error.
// If there is an error, returns `fallback` and the error.
func GetBool(name string, fallback bool) (bool, error) {
s := os.Getenv(name)
if s == "" {
return fallback, nil
}
v, err := strconv.ParseBool(s)
if err != nil {
return fallback, fmt.Errorf("get bool %s: %w", name, err)
}
return v, nil
}
// GetInt fetches and parses an integer typed environment variable
//
// If the variable is empty, returns `fallback` and no error.
// If there is an error, returns `fallback` and the error.
func GetInt(name string, fallback int) (int, error) {
s := os.Getenv(name)
if s == "" {
return fallback, nil
}
v, err := strconv.Atoi(s)
if err != nil {
return fallback, fmt.Errorf("get int %s: %w", name, err)
}
return v, nil
}
// GetDuration fetches and parses a duration typed environment variable
func GetDuration(name string, fallback time.Duration) (time.Duration, error) {
s := os.Getenv(name)
if s == "" {
return fallback, nil
}
v, err := time.ParseDuration(s)
if err != nil {
return fallback, fmt.Errorf("get duration %s: %w", name, err)
}
return v, nil
}
// GetString fetches a given name from the environment and falls back to a
// default value if the name is not available. The value is stripped of
// leading and trailing whitespace.
func GetString(name string, fallback string) string {
value := os.Getenv(name)
if value == "" {
return fallback
}
return strings.TrimSpace(value)
}
// ExtractValue returns the value of the environment variable with the given key. The given key
// should not have a trailing "=". If the same key occurrs multiple times in the environment, then
// any later occurrences will override previous ones.
func ExtractValue(environment []string, key string) string {
var value string
for _, envvar := range environment {
if strings.HasPrefix(envvar, key+"=") {
value = strings.TrimPrefix(envvar, key+"=")
}
}
return value
}
|