-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
53 lines (42 loc) · 1.08 KB
/
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
51
52
53
package repository
import (
"fmt"
_ "github.com/jinzhu/gorm/dialects/postgres"
"go.uber.org/zap"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"time"
)
func NewPostgresDB(DBUser, DBPassword, DBName, DBHost, DBPort string, loggerSugar *zap.SugaredLogger) *gorm.DB {
var err error
conString := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
DBHost,
DBPort,
DBUser,
DBPassword,
DBName)
loggerSugar.Infow("db connection", "connection_string", conString)
DB, err := connecting(conString, loggerSugar)
if err != nil {
log.Panic(err)
}
return DB
}
func connecting(conString string, loggerSugar *zap.SugaredLogger) (*gorm.DB, error) {
tryConnect := 1
for {
loggerSugar.Infow("trying starts postgres db", "try", tryConnect)
DB, err := gorm.Open(postgres.Open(conString), &gorm.Config{})
if err != nil && tryConnect != 3 {
tryConnect++
if tryConnect > 3 {
loggerSugar.Infow("error to starts the postgres db", "tries to starts", tryConnect)
return nil, err
}
time.Sleep(3 * time.Second)
continue
}
return DB, err
}
}