From 1a93d5d9f3d119324ccd9e8070da077aea06f7f3 Mon Sep 17 00:00:00 2001 From: brent saner Date: Fri, 6 Sep 2024 12:50:23 -0400 Subject: [PATCH] v1.6.0 ADDED: - env/DefEnv(), env/DefEnvBlank() --- envs/funcs.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/envs/funcs.go b/envs/funcs.go index 6676ade..0d3d2a2 100644 --- a/envs/funcs.go +++ b/envs/funcs.go @@ -17,6 +17,34 @@ import ( `r00t2.io/sysutils/paths` ) +/* + DefEnv operates like Python's .get() method on dicts (maps); + if the environment variable specified by key does not exist/is not specified, + then the value specified by fallback will be returned instead + otherwise key's value is returned. +*/ +func DefEnv(key, fallback string) (value string) { + + var exists bool + + if value, exists = os.LookupEnv(key); !exists { + value = fallback + } + + return +} + +// DefEnvBlank is like DefEnv but will ADDITIONALLY/ALSO apply fallback if key is *defined/exists but is an empty string*. +func DefEnvBlank(key, fallback string) (value string) { + + value = DefEnv(key, fallback) + if value == "" { + value = fallback + } + + return +} + // GetEnvMap returns a map of all environment variables. All values are strings. func GetEnvMap() (envVars map[string]string) {