Restructure app

This commit is contained in:
Eden Kirin
2023-10-25 17:55:36 +02:00
parent 7fdf131d53
commit 34b2f55cfc
5 changed files with 26 additions and 32 deletions

52
app/db.go Normal file
View File

@ -0,0 +1,52 @@
package main
import (
"fmt"
"strconv"
"strings"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
)
const CONNECTION_MAX_IDLE_TIME = time.Minute * 1
const DB_CONNECTION_TIMEOUT = 5
var DBConn *gorm.DB
func InitDB() *gorm.DB {
var connectionString = strings.Join([]string{
"postgres://",
Config.Database.Username, ":",
Config.Database.Password, "@",
Config.Database.Host, ":",
Config.Database.Port, "/",
Config.Database.Name,
"?sslmode=disable",
"&TimeZone=UTC",
"&connect_timeout=", strconv.Itoa(DB_CONNECTION_TIMEOUT),
}, "")
var logLevel = gormLogger.Silent
if Config.Application.DebugSQL {
logLevel = gormLogger.Info
}
var err error
DBConn, err = gorm.Open(postgres.Open(connectionString), &gorm.Config{
Logger: gormLogger.Default.LogMode(logLevel),
})
if err != nil {
msg := fmt.Sprintf("Error connecting to database: %s. Terminating!", err)
Log.Error(msg)
panic(msg)
}
// set connection autodisconnect after idle time
db, _ := DBConn.DB()
db.SetConnMaxIdleTime(CONNECTION_MAX_IDLE_TIME)
return DBConn
}