// Command api is the HTTP entrypoint of the messenger backend. // // It wires configuration, logging and the HTTP server together and // supports graceful shutdown on SIGINT/SIGTERM. package main import ( "context" "errors" "net/http" "os" "os/signal" "syscall" "time" "messenger/internal/auth" "messenger/internal/media" "messenger/internal/platform/config" "messenger/internal/platform/logger" "messenger/internal/realtime" "messenger/internal/server" "messenger/internal/store" "github.com/jackc/pgx/v5/pgxpool" ) func main() { log := logger.New() cfg, err := config.Load() if err != nil { log.Error("invalid configuration", "error", err) os.Exit(1) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() pool, err := pgxpool.New(ctx, cfg.DatabaseURL) if err != nil { log.Error("failed to create db pool", "error", err) os.Exit(1) } defer pool.Close() st := store.New(pool) if err := st.Migrate(ctx); err != nil { log.Error("database migration failed", "error", err) os.Exit(1) } log.Info("database ready") tm := auth.NewTokenManager(cfg.JWTSecret) hub := realtime.NewHub(st) mediaStore, err := media.NewLocal(cfg.MediaDir) if err != nil { log.Error("failed to init media storage", "error", err) os.Exit(1) } httpServer := server.New(cfg, log, st, tm, hub, mediaStore) // Run the server in a goroutine so that shutdown can be triggered // from the signal handler below. go func() { log.Info("http server listening", "addr", cfg.HTTPAddr, "static_dir", cfg.StaticDir, "env", cfg.Environment, ) if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Error("http server failed", "error", err) os.Exit(1) } }() // Wait for a termination signal, then drain in-flight requests. <-ctx.Done() log.Info("shutting down") shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { log.Error("graceful shutdown failed", "error", err) os.Exit(1) } log.Info("server stopped cleanly") }