-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres.go
50 lines (40 loc) · 962 Bytes
/
postgres.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 db
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var database *gorm.DB
type Config struct {
Host string
Port string
Username string
Password string
DBName string
SSLMode string
}
func initDB(config Config) *gorm.DB {
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
config.Host, config.Port, config.Username, config.Password, config.DBName, config.SSLMode)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}
func StartDbConnection(config Config) {
database = initDB(config)
}
func GetDBConn() *gorm.DB {
return database
}
func CloseDbConnection() error {
db, err := database.DB()
if err != nil {
return fmt.Errorf("error occured on database connection closing: %s", err.Error())
}
if err := db.Close(); err != nil {
return fmt.Errorf("error occured on database connection closing: %s", err.Error())
}
return nil
}