From dcf777bf08d3ccc83dcef354b128253f061f9d5c Mon Sep 17 00:00:00 2001 From: lash Date: Sun, 12 Jan 2025 10:24:50 +0000 Subject: [PATCH] Fix missing err in config --- config/config.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ env/load.go | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 config/config.go create mode 100644 env/load.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..bd7d045 --- /dev/null +++ b/config/config.go @@ -0,0 +1,59 @@ +package config + +import ( + "strings" + + "git.grassecon.net/grassrootseconomics/visedriver/env" +) + +var ( + defaultLanguage = "eng" + languages []string +) + +var ( + DbConn string + DefaultLanguage string + Languages []string +) + +func setLanguage() error { + defaultLanguage = env.GetEnv("DEFAULT_LANGUAGE", defaultLanguage) + languages = strings.Split(env.GetEnv("LANGUAGES", defaultLanguage), ",") + haveDefaultLanguage := false + for i, v := range(languages) { + languages[i] = strings.ReplaceAll(v, " ", "") + if languages[i] == defaultLanguage { + haveDefaultLanguage = true + } + } + + if !haveDefaultLanguage { + languages = append([]string{defaultLanguage}, languages...) + } + + return nil +} + + + +func setConn() error { + DbConn = env.GetEnv("DB_CONN", "") + return nil +} + +// LoadConfig initializes the configuration values after environment variables are loaded. +func LoadConfig() error { + err := setConn() + if err != nil { + return err + } + err = setLanguage() + if err != nil { + return err + } + DefaultLanguage = defaultLanguage + Languages = languages + + return nil +} 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 +}