-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
39 lines (31 loc) · 848 Bytes
/
database.go
File metadata and controls
39 lines (31 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// DB is the global database connection
var DB *gorm.DB
// InitDB initializes the GORM DB connection using env variables.
func InitDB() {
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
user := os.Getenv("DB_USER")
password := os.Getenv("DB_PASSWORD")
name := os.Getenv("DB_NAME")
sslmode := os.Getenv("DB_SSLMODE")
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
host, port, user, password, name, sslmode)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("failed to connect database: %v", err)
}
// Run automigrations
err = db.AutoMigrate(&User{}, &Product{}, &Order{}, &OrderItem{})
if err != nil {
log.Fatalf("auto migrate failed: %v", err)
}
DB = db
}