diff --git a/env/load.go b/env/load.go new file mode 100644 index 0000000..f0bbd7f --- /dev/null +++ b/env/load.go @@ -0,0 +1,40 @@ +package env + +import ( + "log" + "os" + "path" + "strconv" + + "github.com/joho/godotenv" +) + +func LoadEnvVariables() { + LoadEnvVariablesPath(".") +} + +func LoadEnvVariablesPath(dir string) { + fp := path.Join(dir, ".env") + err := godotenv.Load(fp) + if err != nil { + log.Fatal("Error loading .env file", err) + } +} + +// Helper to get environment variables with a default fallback +func GetEnv(key, defaultVal string) string { + if value, exists := os.LookupEnv(key); exists { + return value + } + return defaultVal +} + +// Helper to safely convert environment variables to uint +func GetEnvUint(key string, defaultVal uint) uint { + if value, exists := os.LookupEnv(key); exists { + if parsed, err := strconv.Atoi(value); err == nil && parsed >= 0 { + return uint(parsed) + } + } + return defaultVal +} diff --git a/go.mod b/go.mod index 43e268d..5c9c567 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,7 @@ module git.grassecon.net/grassrootseconomics/common go 1.23.4 -require golang.org/x/crypto v0.32.0 +require ( + github.com/joho/godotenv v1.5.1 + golang.org/x/crypto v0.32.0 +) diff --git a/go.sum b/go.sum index 2f9c45b..8cd4169 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,4 @@ +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=