-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
59 lines (46 loc) · 1.3 KB
/
connection.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
54
55
56
57
58
59
package config
import (
"fmt"
_ "github.com/lib/pq"
"github.com/spf13/viper"
"github.com/tamahavik/tasker-api/pkg/models"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Connection interface {
GetConnection() (*gorm.DB, error)
}
type ConnectionImpl struct {
}
func NewConnection() Connection {
return &ConnectionImpl{}
}
func (c ConnectionImpl) GetConnection() (*gorm.DB, error) {
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=%s",
viper.GetString("DB_HOST"),
viper.GetString("DB_USER"),
viper.GetString("DB_PASSWORD"),
viper.GetString("DB_NAME"),
viper.GetString("DB_PORT"),
viper.GetString("SSL_MODE"),
viper.GetString("TZ"))
db, err1 := gorm.Open(postgres.New(postgres.Config{DSN: dsn}), &gorm.Config{})
if err1 != nil {
return nil, err1
}
fmt.Println(viper.GetString("DB"))
err2 := db.AutoMigrate(&models.User{})
if err2 != nil {
return nil, err2
}
sqlDriver, err3 := db.DB()
if err3 != nil {
return nil, err3
}
sqlDriver.SetMaxIdleConns(viper.GetInt("MAX_IDLE_CON"))
sqlDriver.SetMaxOpenConns(viper.GetInt("MAX_OPEN_CON"))
sqlDriver.SetConnMaxIdleTime(time.Duration(viper.GetInt("CON_MAX_IDLE_TIME")) * time.Minute)
sqlDriver.SetConnMaxLifetime(time.Duration(viper.GetInt("CON_MAX_LIFE_TIME")) * time.Minute)
return db, nil
}