feat(redis): session repository with native TTL and main connection

This commit is contained in:
Голиков Maximillian Антон
2026-10-02 14:02:55 +03:00
parent 5a3f6114a4
commit 812efa67bb
4 changed files with 166 additions and 6 deletions
+28 -6
View File
@@ -7,15 +7,18 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"high-loud-apps-labs/internal/config"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi"
"high-loud-apps-labs/internal/httpapi/handler"
"high-loud-apps-labs/internal/httpapi/middleware"
"high-loud-apps-labs/internal/service"
"high-loud-apps-labs/internal/storage/postgres"
redisstore "high-loud-apps-labs/internal/storage/redis"
)
func main() {
@@ -46,10 +49,13 @@ func main() {
store := postgres.New(pool)
sessionRepo, closeSession := newSessionRepo(cfg, store)
defer closeSession()
hasher := service.NewArgon2idHasher()
userSvc := service.NewUserService(store.Users(), hasher)
sessionSvc := service.NewSessionService(store.Users(), store.Sessions(), hasher, cfg.SessionTTL)
sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL)
chatSvc := service.NewChatService(store.Chats(), store.Users())
messageSvc := service.NewMessageService(store.Messages(), store.Chats())
@@ -64,13 +70,10 @@ func main() {
middleware.BearerAuth(sessionSvc),
)
srv := &http.Server{
Addr: addr,
Handler: router,
}
srv := &http.Server{Addr: addr, Handler: router}
go func() {
log.Printf("Запускаем на %s", addr)
log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Ошибка запуска: %v", err)
}
@@ -88,3 +91,22 @@ func main() {
}
log.Println("Сервер остановлен")
}
func newSessionRepo(cfg *config.Config, store *postgres.Storage) (domain.SessionRepository, func()) {
switch strings.ToLower(cfg.SessionStore) {
case "", "postgres":
return store.Sessions(), func() {}
case "redis", "valkey":
if cfg.CacheURL == "" {
log.Fatalf("SESSION_STORE=%s требует CACHE_URL_FILE или CACHE_URL", cfg.SessionStore)
}
client, err := redisstore.NewClient(cfg.CacheURL)
if err != nil {
log.Fatalf("redis: %v", err)
}
return redisstore.NewSessionRepo(client), func() { _ = client.Close() }
default:
log.Fatalf("SESSION_STORE=%q не поддерживается", cfg.SessionStore)
return nil, nil
}
}