From e861ff4c5726f1491b3e45d69fc63d8d212df4fc Mon Sep 17 00:00:00 2001 From: Yuefii Date: Tue, 20 Aug 2024 15:59:18 +0700 Subject: [PATCH] fix: load env config --- cmd/web/main.go | 16 +++++++--------- database/config.go | 6 ------ pkg/utils/load_env.go | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 15 deletions(-) create mode 100644 pkg/utils/load_env.go diff --git a/cmd/web/main.go b/cmd/web/main.go index fdf18ff..6f4ea0b 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -3,16 +3,19 @@ package main import ( "fmt" "log" + "ngodeyuk-core/database" + "ngodeyuk-core/internal/infrastructure/routes" + "ngodeyuk-core/pkg/utils" "path/filepath" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" - "github.com/joho/godotenv" - - "ngodeyuk-core/database" - "ngodeyuk-core/internal/infrastructure/routes" ) +func init() { + utils.LoadEnv() +} + func main() { route := gin.Default() config := cors.DefaultConfig() @@ -22,11 +25,6 @@ func main() { route.Use(cors.New(config)) - err := godotenv.Load() - if err != nil { - log.Fatalf("error load .env file: %v", err) - } - db, err := database.InitDB() if err != nil { panic("failed to connect database.") diff --git a/database/config.go b/database/config.go index 6ff1c75..5a97eb8 100644 --- a/database/config.go +++ b/database/config.go @@ -4,17 +4,11 @@ import ( "log" "os" - "github.com/joho/godotenv" "gorm.io/driver/postgres" "gorm.io/gorm" ) func InitDB() (*gorm.DB, error) { - err := godotenv.Load() - if err != nil { - log.Fatalf("Error loading .env file: %v", err) - } - dsn := "host=" + os.Getenv("DB_HOST") + " user=" + os.Getenv("DB_USER") + " password=" + os.Getenv("DB_PASSWORD") + diff --git a/pkg/utils/load_env.go b/pkg/utils/load_env.go new file mode 100644 index 0000000..0002311 --- /dev/null +++ b/pkg/utils/load_env.go @@ -0,0 +1,14 @@ +package utils + +import ( + "log" + + "github.com/joho/godotenv" +) + +func LoadEnv() { + err := godotenv.Load() + if err != nil { + log.Fatal("Error loading .env file") + } +}