Restructure again

This commit is contained in:
Eden Kirin
2023-10-26 16:49:24 +02:00
parent 7512d75a4d
commit dd671d561c
5 changed files with 32 additions and 27 deletions

99
app/lib/cfg/config.go Normal file
View File

@ -0,0 +1,99 @@
package cfg
import (
"fmt"
"os"
"github.com/kelseyhightower/envconfig"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
type configStruct struct {
Application struct {
SecretKey string `yaml:"secretKey" json:"-"`
LogLevel string `yaml:"logLevel"`
LogFile string `yaml:"logFile"`
Debug bool `yaml:"debug"`
DebugSQL bool `yaml:"debugSQL"`
DisableSendMail bool `yaml:"disableSendMail"`
IsProduction bool `yaml:"isProduction"`
LoopDelay uint32 `yaml:"loopDelay"`
} `yaml:"application"`
Database struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
Name string `yaml:"name"`
Username string `yaml:"username"`
Password string `yaml:"password" json:"-"`
} `yaml:"database"`
Redis struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password" json:"-"`
Database string `yaml:"database"`
Prefix string `yaml:"prefix"`
} `yaml:"redis"`
SMTP struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password" json:"-"`
StartTLS bool `yaml:"startTLS"`
UseTLS bool `yaml:"useTLS"`
FromEmail string `yaml:"fromEmail"`
} `yaml:"smtp"`
}
const DEFAULT_CONFIG_FILE = "config.yaml"
const ENV_PREFIX = "MAILSENDER"
var Config configStruct
var log = logrus.New()
func processError(err error) {
log.Error("Config file error: " + err.Error())
os.Exit(2)
}
func readFile(cfgFile string, cfg *configStruct) {
f, err := os.Open(cfgFile)
if err != nil {
processError(err)
} else {
decoder := yaml.NewDecoder(f)
err = decoder.Decode(cfg)
if err != nil {
processError(err)
}
}
defer f.Close()
}
func readEnv(cfg *configStruct) {
err := envconfig.Process(ENV_PREFIX, cfg)
if err != nil {
processError(err)
}
}
func InitCfg() {
cfgFile := os.Getenv("MAILSENDER_CONFIG")
if cfgFile == "" {
cfgFile = DEFAULT_CONFIG_FILE
}
readFile(cfgFile, &Config)
readEnv(&Config)
maskedCfg := Config
maskedCfg.Database.Password = "**password hidden**"
maskedCfg.Redis.Password = "**password hidden**"
maskedCfg.SMTP.Password = "**password hidden**"
maskedCfg.Application.SecretKey = "**secret key hidden**"
fmt.Println("--- CONFIG -------------------------------")
fmt.Println(maskedCfg)
fmt.Println("------------------------------------------")
}

57
app/lib/db/db.go Normal file
View File

@ -0,0 +1,57 @@
package db
import (
"fmt"
"iris-test/app/lib/cfg"
"iris-test/app/lib/logging"
"iris-test/app/repository"
"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)
repository.Dao = repository.CreateDAO(DBConn)
return DBConn
}

View File

@ -0,0 +1,65 @@
package logging
import (
"encoding/json"
"fmt"
"io"
"iris-test/app/lib/cfg"
"os"
"github.com/sirupsen/logrus"
)
var Log = logrus.New()
func Debug(message string) {
Log.Debug(message)
}
func Info(message string) {
Log.Info(message)
}
func Error(message string) {
Log.Error(message)
}
func Warn(message string) {
Log.Warn(message)
}
func InitLogging() {
logLevel, err := logrus.ParseLevel(cfg.Config.Application.LogLevel)
if err != nil {
panic(fmt.Sprintf("Invalid configured logLevel: %s\n", cfg.Config.Application.LogLevel))
}
Log.SetLevel(logLevel)
Log.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
PadLevelText: true,
DisableQuote: true,
})
LogFile := cfg.Config.Application.LogFile
file, err := os.OpenFile(
LogFile,
os.O_CREATE|os.O_WRONLY|os.O_APPEND,
0655,
)
if err != nil {
msg := fmt.Sprintf("Failed to log to file %s: %s", cfg.Config.Application.LogFile, err)
Log.Warning(msg)
panic(msg)
}
mw := io.MultiWriter(os.Stdout, file)
Log.SetOutput(mw)
configJson, err := json.Marshal(cfg.Config)
if err == nil {
Info(fmt.Sprintf("Using config: %s", configJson))
}
}