forked from mtusi2026/mtusi2026lab3
74 lines
1.7 KiB
Go
Executable File
74 lines
1.7 KiB
Go
Executable File
// Command server starts the messenger HTTP API, applies optional migrations,
|
|
// and shuts down gracefully on SIGINT/SIGTERM.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/database"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/health"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
|
|
)
|
|
|
|
func main() {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
log.Fatalf("configuration: %v", err)
|
|
}
|
|
|
|
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
pool, err := database.Connect(rootCtx, cfg.DatabaseURL, cfg.DBMaxConns, cfg.StartupWait)
|
|
if err != nil {
|
|
log.Fatalf("database: %v", err)
|
|
}
|
|
defer pool.Close()
|
|
|
|
if cfg.MigrateOnly || cfg.RunMigrations {
|
|
if err = database.Migrate(cfg.DatabaseURL); err != nil {
|
|
log.Fatalf("migrations: %v", err)
|
|
}
|
|
}
|
|
|
|
if cfg.MigrateOnly {
|
|
log.Printf("migrations applied; migrate-only process exiting")
|
|
return
|
|
}
|
|
|
|
sessions, err := session.New(cfg.CacheURL, cfg.SessionTTL, cfg.RedisTimeout)
|
|
if err != nil {
|
|
log.Fatalf("session store: %v", err)
|
|
}
|
|
defer sessions.Close()
|
|
|
|
app := internal.New(cfg, pool, sessions)
|
|
|
|
addr := net.JoinHostPort(cfg.Host, cfg.Port)
|
|
listenErr := make(chan error, 1)
|
|
go func() {
|
|
listenErr <- app.Listen(addr)
|
|
}()
|
|
|
|
select {
|
|
case err = <-listenErr:
|
|
if err != nil {
|
|
log.Fatalf("server: %v", err)
|
|
}
|
|
case <-rootCtx.Done():
|
|
}
|
|
|
|
log.Printf("shutting down")
|
|
health.SignalShutdown()
|
|
if err = app.ShutdownWithTimeout(10 * time.Second); err != nil {
|
|
log.Printf("shutdown: %v", err)
|
|
}
|
|
}
|