pcmt/app/app.go
leo c4d0cb209b
All checks were successful
continuous-integration/drone/push Build is passing
go: add settings struct
* let the settings struct be the single source of truth
* rm app fields that are covered by settings
* pass around a pointer to settings instead of config
* consolidate config+flags into settings on start-up
* update tests
* rm empty settings.go file

fixes #4
2023-05-03 02:18:29 +02:00

121 lines
2.6 KiB
Go

package app
import (
"embed"
"errors"
"git.dotya.ml/mirre-mt/pcmt/app/settings"
"git.dotya.ml/mirre-mt/pcmt/ent"
"git.dotya.ml/mirre-mt/pcmt/slogging"
"github.com/labstack/echo/v4"
)
type App struct {
e *echo.Echo
logger *slogging.Logger
initialised bool
embeds Embeds
templatesPath string
assetsPath string
setting *settings.Settings
jwtkey string //nolint:unused
encryptionKey string //nolint:unused
dbConnect string //nolint:unused
db *ent.Client
}
type Embeds struct {
templates embed.FS
assets embed.FS
}
// Init allows setting App's important fields - once.
func (a *App) Init(s *settings.Settings, logger *slogging.Logger, dbclient *ent.Client) error {
if !a.initialised {
e := echo.New()
a.e = e
a.logger = logger
a.setting = s
if a.setting.IsDevel() {
a.setDevel()
}
a.Logger().Infof("app version: %s", a.setting.Version())
a.Logger().Info("saving db connection string")
a.db = dbclient
if a.templatesPath == "" {
a.templatesPath = "templates"
a.setting.SetTemplatesPath("templates")
} else {
a.setting.SetTemplatesPath(a.templatesPath)
}
if a.assetsPath == "" {
a.assetsPath = "assets"
a.setting.SetAssetsPath("assets")
} else {
a.setting.SetAssetsPath(a.assetsPath)
}
a.initialised = true
a.Logger().Info("app initialised")
return nil
}
return errors.New("ErrAppAlreadyInitialised")
}
// E returns app's *echo.Echo instance.
func (a *App) E() *echo.Echo {
return a.e
}
// Logger returns app's logger instance.
func (a *App) Logger() *slogging.Logger {
return a.logger
}
// PrintConfiguration outputs relevant settings of the application to console.
func (a *App) PrintConfiguration() {
if a.setting != nil {
if a.setting.IsLive() {
a.Logger().Info("app config: live mode enabled")
}
if a.setting.IsDevel() {
a.Logger().Info("app config: devel mode enabled - make sure that browser-sync is running")
}
return
}
panic(errors.New("somehow we got here with config unset - contact the developer"))
}
func (a *App) SetSettings(s *settings.Settings) {
a.setting = s
}
// SetEmbeds saves the embedded files to application state.
func (a *App) SetEmbeds(templates, assets embed.FS) {
a.logger.Info("setting embeds")
a.embeds.templates = templates
a.embeds.assets = assets
}
// setDevel puts the app in devel mode, which loads a browser-sync script in
// templates and expects browser-sync running.
func (a *App) setDevel() {
a.Logger().Info("enabling debug logging for Echo")
a.e.Debug = true
a.logger = slogging.SetLevel(slogging.LevelDebug)
a.Logger().Debug("enabled debug logging for the default logger")
}