52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func NewDatabase() *gorm.DB {
|
|
username := os.Getenv("DB_USERNAME")
|
|
password := "123$Nt1"
|
|
port, err := strconv.Atoi(os.Getenv("DB_PORT"))
|
|
if err != nil {
|
|
fmt.Println("error ", err.Error())
|
|
}
|
|
host := os.Getenv("DB_HOST")
|
|
database := os.Getenv("DB_NAME")
|
|
idleConnection := 10
|
|
maxConnection := 100
|
|
maxLifeTimeConnection := 300
|
|
|
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Jakarta", host, username, password, database, port)
|
|
|
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
|
|
// Logger: logger.New(&logrusWriter{Logger: log}, logger.Config{
|
|
// SlowThreshold: time.Second * 5,
|
|
// Colorful: false,
|
|
// IgnoreRecordNotFoundError: true,
|
|
// ParameterizedQueries: true,
|
|
// LogLevel: logger.Info,
|
|
// }),
|
|
})
|
|
if err != nil {
|
|
fmt.Println("failed to connect database: ", err)
|
|
}
|
|
|
|
connection, err := db.DB()
|
|
if err != nil {
|
|
fmt.Println("failed to connect database: ", err)
|
|
}
|
|
|
|
connection.SetMaxIdleConns(idleConnection)
|
|
connection.SetMaxOpenConns(maxConnection)
|
|
connection.SetConnMaxLifetime(time.Second * time.Duration(maxLifeTimeConnection))
|
|
|
|
return db
|
|
}
|