36 lines
663 B
Go
36 lines
663 B
Go
package initializers
|
|
|
|
import (
|
|
"os"
|
|
|
|
"github.com/joho/godotenv"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var DB *gorm.DB
|
|
|
|
func ConnectToDb() {
|
|
var err error
|
|
|
|
// Load the .env file
|
|
err = godotenv.Load()
|
|
if err != nil {
|
|
panic("Error loading .env file")
|
|
}
|
|
|
|
dsn := "host=" + os.Getenv("DB_HOST") +
|
|
" user=" + os.Getenv("DB_USER") +
|
|
" password=" + os.Getenv("DB_PASSWORD") +
|
|
" dbname=" + os.Getenv("DB_NAME") +
|
|
" port=" + os.Getenv("DB_PORT") +
|
|
" sslmode=" + os.Getenv("DB_SSLMODE") +
|
|
" TimeZone=" + os.Getenv("DB_TIMEZONE")
|
|
|
|
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
|
|
if err != nil {
|
|
panic("Failed to connect to DB")
|
|
}
|
|
}
|