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