From b0339d13b2a0fdf0f77f020e2e339b982e0124d0 Mon Sep 17 00:00:00 2001 From: Jan Barfuss Date: Sat, 14 Dec 2024 12:50:54 +0100 Subject: [PATCH] Added config for env & .env for the database connection --- config/config.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ go.mod | 2 ++ go.sum | 2 ++ 3 files changed, 49 insertions(+) create mode 100644 config/config.go create mode 100644 go.sum diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..53af835 --- /dev/null +++ b/config/config.go @@ -0,0 +1,45 @@ +package config + +import ( + "fmt" + "os" + "strings" + + "github.com/joho/godotenv" +) + +func Load() map[string]string { + var env map[string]string = make(map[string]string) + + validEnv := []string{"DB_USER", "DB_PASSWORD", "DB_NAME", "DB_HOST", "DB_PORT"} + + envpath := "./.env" + + if _, err := os.Stat(envpath); err == nil { + + dotenv, err := godotenv.Read(envpath) + if err != nil { + fmt.Println("Error loading .env file: ", err) + } + + env = dotenv + } else { + fmt.Println("No .env file found", err) + } + + for _, key := range validEnv { + tempenv := os.Getenv(key) + if tempenv != "" { + env[key] = tempenv + } + } + + if len(env) == 0 { + fmt.Println("no environment variables are set") + os.Exit(1) + } + + // TODO: check if all the required environment variables are set + return env +} + diff --git a/go.mod b/go.mod index 81e7457..204d4bb 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/LeRoid-hub/Bookholder-API go 1.22.1 + +require github.com/joho/godotenv v1.5.1 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d61b19e --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=