Files
mtusi2026lab2-fork/cmd/messenger/main.go
2026-10-01 16:53:27 +03:00

81 lines
2.0 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"mtusi-messenger/src/api"
"mtusi-messenger/src/config"
"mtusi-messenger/src/domain"
)
func main() {
cfg := config.Load()
if cfg.DatabaseURL == "" {
log.Fatal("DATABASE_URL is required (env DATABASE_URL or DATABASE_URL_FILE)")
}
rootCtx, cancelRoot := context.WithCancel(context.Background())
defer cancelRoot()
store, err := domain.NewStore(rootCtx, cfg.DatabaseURL)
if err != nil {
log.Fatalf("postgres: %v", err)
}
defer store.Close()
// Кэш сессий в Redis/Valkey. Если CACHE_URL не задан — работаем без кэша.
var cache *domain.SessionCache
if cfg.CacheURL != "" {
cache, err = domain.NewSessionCache(rootCtx, cfg.CacheURL)
if err != nil {
if cfg.RedisRequired {
log.Fatalf("redis required but unavailable: %v", err)
}
log.Printf("redis unavailable, continuing without session cache: %v", err)
cache = nil
} else {
defer cache.Close()
}
} else if cfg.RedisRequired {
log.Fatal("SESSION_STORE=redis but CACHE_URL is not configured")
}
sessions := domain.NewSessionStore(store, cache, cfg.SessionTTL)
handler := &api.Handler{Store: store, Sessions: sessions}
router := api.NewRouter(handler)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
Handler: router,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
go func() {
log.Printf("messenger listening on %s (env=%s, session_ttl=%s)", srv.Addr, cfg.Env, cfg.SessionTTL)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
}()
<-stop
log.Println("shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
log.Println("stopped")
}