Bookholder-API/config/config.go

70 lines
1.2 KiB
Go
Raw Normal View History

package config
import (
"fmt"
"os"
"github.com/joho/godotenv"
)
func Load() map[string]string {
var env map[string]string = make(map[string]string)
2024-12-20 13:28:54 +00:00
validEnv := []string{"DB_USER", "DB_PASSWORD", "DB_NAME", "DB_HOST", "DB_PORT", "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)
}
2024-12-14 14:51:29 +00:00
checkDB(env)
return env
}
2024-12-14 14:51:29 +00:00
func checkDB(env map[string]string) {
2024-12-20 13:28:54 +00:00
required := []string{"DB_USER", "DB_PASSWORD", "DB_HOST", "DB_PORT"}
optional := []string{"DB_NAME"}
defaults := []string{"bookholder"}
2024-12-14 14:51:29 +00:00
for _, item := range required {
checkEnv(item, env)
}
2024-12-20 13:28:54 +00:00
for i, item := range optional {
if _, ok := env[item]; !ok {
env[item] = defaults[i]
}
}
2024-12-14 14:51:29 +00:00
}
func checkEnv(check string, env map[string]string) {
if val, ok := env[check]; ok {
if val == "" {
fmt.Println(check, "is not set")
os.Exit(1)
}
} else {
fmt.Println(check, "is not set")
os.Exit(1)
}
}