Added config for env & .env for the database connection

This commit is contained in:
Jan Barfuss 2024-12-14 12:50:54 +01:00
parent 2c7445d9ba
commit b0339d13b2
3 changed files with 49 additions and 0 deletions

45
config/config.go Normal file
View File

@ -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
}

2
go.mod
View File

@ -1,3 +1,5 @@
module github.com/LeRoid-hub/Bookholder-API
go 1.22.1
require github.com/joho/godotenv v1.5.1 // indirect

2
go.sum Normal file
View File

@ -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=