nettools/env/env.go
2024-11-12 09:10:09 +01:00

64 lines
1.5 KiB
Go

package env_utils
import (
"log"
"os"
"strings"
common "nettools/common"
)
func Getenv(envName string) (env string, ok bool) {
env = os.Getenv(envName)
return env, env != ""
}
func MustGetenv(envName string) (env string) {
env = os.Getenv(envName)
if env == "" {
log.Panicf("Panic while parsing environment variable %s: variable wasn't set or is an empty string", envName)
}
return env
}
func GetenvBool(envName string) (env bool, ok bool) {
envStr := os.Getenv(envName)
lcEnvStr := strings.ToLower(envStr)
if lcEnvStr == "true" || lcEnvStr == "yes" || lcEnvStr == "y" {
return true, true
} else if lcEnvStr == "false" || lcEnvStr == "no" || lcEnvStr == "n" {
return false, true
}
return false, false
}
func GetenvOrDefaultAndIsEnv(envName string, defaultVal string) (out string, isEnv bool) {
envPlainData := os.Getenv(envName)
if envPlainData == "" {
return defaultVal, false
}
return envPlainData, true
}
func GetenvOrDefaultStr(envName string, defaultVal string) string {
env := os.Getenv(envName)
return common.Ternar(env != "", env, defaultVal)
}
func GetenvOrDefaultInt[i common.Int](envName string, base int, bitSize int, defaultVal i) i {
intStr, ok := Getenv(envName)
if !ok {
return defaultVal
}
res, err := common.Str2Int[i](intStr, base, bitSize)
if err != nil {
return defaultVal
}
return res
}
func GetenvOrDefaultBool(envName string, defaultVal bool) bool {
env, ok := GetenvBool(envName)
return common.Ternar(ok, env, defaultVal)
}