-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
50 lines (39 loc) · 999 Bytes
/
base.go
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
40
41
42
43
44
45
46
47
48
49
50
package models
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv"
"os"
)
var db *gorm.DB
func init() {
e := godotenv.Load()
if e != nil && os.Getenv("environment") == "" {
fmt.Printf("Error loading .env file: %s\n", e)
}
username := os.Getenv("db_user")
password := os.Getenv("db_pass")
dbName := os.Getenv("db_name")
dbHost := os.Getenv("db_host")
environment := os.Getenv("environment")
fmt.Println("Environment: ", environment)
dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password)
fmt.Println(dbUri)
conn, err := gorm.Open("postgres", dbUri)
if err != nil {
fmt.Print(err)
}
db = conn
if environment == "testing" {
db.Delete(Account{})
db.Delete(Book{})
db.Delete(Review{})
db.Debug().AutoMigrate(&Account{}, &Book{}, &Review{})
} else {
db.AutoMigrate(&Account{}, &Book{}, &Review{})
}
}
func GetDB() *gorm.DB {
return db
}