From 91daec42de7c1e29d400f10ff62c6437bf463c9d Mon Sep 17 00:00:00 2001 From: ae Date: Tue, 1 Apr 2025 12:59:05 +0300 Subject: [PATCH] feat: basic init & startup --- server/main.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/server/main.go b/server/main.go index c131213..96d7798 100644 --- a/server/main.go +++ b/server/main.go @@ -1,9 +1,77 @@ package main import ( - "git.umbrella.haus/ae/notatest/internal" + "context" + "embed" + "os" + + "git.umbrella.haus/ae/notatest/pkg/migrate" + "git.umbrella.haus/ae/notatest/pkg/service" + "github.com/caarlos0/env" + "github.com/jackc/pgx/v5" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" ) -func main() { - internal.Run() +//go:embed sql/migrations/*.sql +var migrationsFS embed.FS + +var ( + isDevelopment = false + config Config +) + +type Config struct { + JWTSecret string `env:"JWT_SECRET,notEmpty"` + HTTPPort string `env:"HTTP_PORT" envDefault:"8080"` + DBURL string `env:"PG_URL,notEmpty"` + RunMode string `env:"GO_ENV" envDefault:"production"` +} + +func init() { + initLogger() + config = Config{} + env.Parse(&config) + + if config.RunMode == "development" { + log.Info().Msg("Development mode enabled") + isDevelopment = true + } + + log.Debug().Msg("Initialization completed") +} + +func main() { + conn, err := pgx.Connect(context.Background(), config.DBURL) + if err != nil { + log.Fatal().Msgf("Failed connecting to database: %s", err) + } + log.Info().Msg("Successfully connected to the database") + log.Debug().Msg(config.DBURL) + + if isDevelopment { + if err := migrate.Run(context.Background(), conn, migrationsFS); err != nil { + log.Fatal().Msgf("Failed running migrations: %s", err) + } + } + + service.Run(conn, config.JWTSecret, config.HTTPPort) +} + +func initLogger() { + logLevel := os.Getenv("LOG_LEVEL") + level, err := zerolog.ParseLevel(logLevel) + if err != nil { + // Default to INFO + level = zerolog.InfoLevel + } + zerolog.SetGlobalLevel(level) + + if isDevelopment { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + } else { + log.Logger = log.Output(os.Stderr) // JSON to stdout/stderr + } + + log.Debug().Msg("Logger initialized") }