From 4c71e83a5eaa99bbddb709913c1d500fb6c6df5b Mon Sep 17 00:00:00 2001 From: masterhc Date: Thu, 25 Jul 2024 16:40:32 +0100 Subject: [PATCH] Feature: Lib folder. Separation of concerns: Lib items are in the lib so that they can be reused. --- controllers/controller.go | 26 ++++---------------------- lib/lib.go | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 22 deletions(-) create mode 100644 lib/lib.go diff --git a/controllers/controller.go b/controllers/controller.go index 18bc347..201d985 100644 --- a/controllers/controller.go +++ b/controllers/controller.go @@ -3,15 +3,11 @@ package controllers import ( "log" "fmt" - "os" "time" "net/http" "encoding/json" - + lib "yaagobackend/lib" "github.com/gorilla/mux" - "github.com/joho/godotenv" - "gorm.io/driver/postgres" - "gorm.io/gorm" ) @@ -60,7 +56,9 @@ func CreateUser(w http.ResponseWriter, r *http.Request) { return } - db, err:=connector() + db, err:= lib.Connector() + + // Auto-migrate the schema db.AutoMigrate(&User{}) @@ -76,19 +74,3 @@ func CreateUser(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Received user: %+v", user) } - -func connector() (*gorm.DB, error) { - // Database connection string - err:= godotenv.Load(); - if(err!=nil) { - log.Fatal("Error loading .env file") - } - dsn := fmt.Sprint(os.Getenv("DATABASE_DSN")) - log.Print(dsn) - // Open the database connection - db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { - log.Fatal("failed to connect database:", err) - } - return db, err -} diff --git a/lib/lib.go b/lib/lib.go new file mode 100644 index 0000000..e25387b --- /dev/null +++ b/lib/lib.go @@ -0,0 +1,27 @@ +package lib + +import( + "log" + "fmt" + "os" + "github.com/joho/godotenv" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + + +func Connector() (*gorm.DB, error) { + // Database connection string + err:= godotenv.Load(); + if(err!=nil) { + log.Fatal("Error loading .env file") + } + dsn := fmt.Sprint(os.Getenv("DATABASE_DSN")) + log.Print(dsn) + // Open the database connection + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatal("failed to connect database:", err) + } + return db, err +}