Initial commit
This commit is contained in:
51
config/db.go
Normal file
51
config/db.go
Normal file
@@ -0,0 +1,51 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user