Feature: Lib folder. Separation of concerns: Lib items are in the lib so that they can be reused.

master
masterhc 8 months ago
parent dae105d15f
commit 4c71e83a5e

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

@ -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
}
Loading…
Cancel
Save