notatest/server/main.go

77 lines
1.6 KiB
Go

package main
import (
"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"
)
//go:embed sql/migrations/*.sql
var migrationsFS embed.FS
var (
isDevelopment = false
config Config
)
type Config struct {
JWTSecret string `env:"JWT_SECRET,notEmpty"`
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)
}
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")
}