Restructure app

This commit is contained in:
Eden Kirin
2023-10-23 23:05:18 +02:00
parent f0e323f2ce
commit 002f6a3d06
11 changed files with 250 additions and 10 deletions

54
app/db/db.go Normal file
View File

@ -0,0 +1,54 @@
package db
import (
"fmt"
"iris-test/app/cfg"
"iris-test/app/logging"
"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://",
cfg.Config.Database.Username, ":",
cfg.Config.Database.Password, "@",
cfg.Config.Database.Host, ":",
cfg.Config.Database.Port, "/",
cfg.Config.Database.Name,
"?sslmode=disable",
"&TimeZone=UTC",
"&connect_timeout=", strconv.Itoa(DB_CONNECTION_TIMEOUT),
}, "")
var logLevel = gormLogger.Silent
if cfg.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)
logging.Error(msg)
panic(msg)
}
// set connection autodisconnect after idle time
db, _ := DBConn.DB()
db.SetConnMaxIdleTime(CONNECTION_MAX_IDLE_TIME)
return DBConn
}