chore(repo): import lab2 sources as lab3 baseline
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"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() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("конфигурация: %v", err)
|
||||
}
|
||||
|
||||
addr := cfg.Host + ":" + cfg.Port
|
||||
|
||||
ctx := context.Background()
|
||||
pool, err := postgres.Connect(ctx, postgres.Config{
|
||||
URL: cfg.DatabaseURL,
|
||||
MaxConns: 10,
|
||||
MinConns: 1,
|
||||
MaxConnLifetime: time.Hour,
|
||||
MaxConnIdleTime: 30 * time.Minute,
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("БД: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
if err := postgres.RunMigrations(ctx, pool); err != nil {
|
||||
log.Fatalf("миграции: %v", err)
|
||||
}
|
||||
|
||||
store := postgres.New(pool)
|
||||
|
||||
sessionRepo, cachePing, closeSession := newSessionRepo(cfg, store)
|
||||
defer closeSession()
|
||||
|
||||
hasher := service.NewArgon2idHasher()
|
||||
|
||||
userSvc := service.NewUserService(store.Users(), hasher)
|
||||
sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL)
|
||||
chatSvc := service.NewChatService(store.Chats(), store.Users())
|
||||
messageSvc := service.NewMessageService(store.Messages(), store.Chats())
|
||||
|
||||
healthChecks := []handler.HealthCheck{
|
||||
func(ctx context.Context) error { return pool.Ping(ctx) },
|
||||
}
|
||||
if cachePing != nil {
|
||||
healthChecks = append(healthChecks, cachePing)
|
||||
}
|
||||
|
||||
router := httpapi.NewRouter(
|
||||
httpapi.Handlers{
|
||||
Health: handler.NewHealthHandler(healthChecks...),
|
||||
User: handler.NewUserHandler(userSvc),
|
||||
Chat: handler.NewChatHandler(chatSvc),
|
||||
Message: handler.NewMessageHandler(messageSvc),
|
||||
Auth: handler.NewAuthHandler(sessionSvc),
|
||||
},
|
||||
middleware.BearerAuth(sessionSvc),
|
||||
)
|
||||
|
||||
srv := &http.Server{Addr: addr, Handler: router}
|
||||
|
||||
go func() {
|
||||
log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("Ошибка запуска: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
log.Println("Получен сигнал завершения, останавливаем сервер...")
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Fatalf("Ошибка при остановке: %v", err)
|
||||
}
|
||||
log.Println("Сервер остановлен")
|
||||
}
|
||||
|
||||
func newSessionRepo(cfg *config.Config, store *postgres.Storage) (domain.SessionRepository, handler.HealthCheck, func()) {
|
||||
switch strings.ToLower(cfg.SessionStore) {
|
||||
case "", "postgres":
|
||||
return store.Sessions(), nil, func() {}
|
||||
case "redis":
|
||||
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)
|
||||
}
|
||||
ping := func(ctx context.Context) error {
|
||||
return client.Ping(ctx).Err()
|
||||
}
|
||||
return redisstore.NewSessionRepo(client), ping, func() { _ = client.Close() }
|
||||
default:
|
||||
log.Fatalf("SESSION_STORE=%q не поддерживается", cfg.SessionStore)
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user