feat(main): wire postgres, sessions and BearerAuth
This commit is contained in:
+32
-13
@@ -10,21 +10,46 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/config"
|
||||
"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/memory"
|
||||
"high-loud-apps-labs/internal/storage/postgres"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := getenv("APP_HOST", "0.0.0.0") + ":" + getenv("APP_PORT", "8080")
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("конфигурация: %v", err)
|
||||
}
|
||||
|
||||
store := memory.New()
|
||||
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)
|
||||
|
||||
hasher := service.NewArgon2idHasher()
|
||||
|
||||
userSvc := service.NewUserService(store.Users(), hasher)
|
||||
sessionSvc := service.NewSessionService(store.Users(), store.Sessions(), hasher, cfg.SessionTTL)
|
||||
chatSvc := service.NewChatService(store.Chats(), store.Users())
|
||||
messageSvc := service.NewMessageService(store.Messages(), store.Chats())
|
||||
|
||||
@@ -34,8 +59,9 @@ func main() {
|
||||
User: handler.NewUserHandler(userSvc),
|
||||
Chat: handler.NewChatHandler(chatSvc),
|
||||
Message: handler.NewMessageHandler(messageSvc),
|
||||
Auth: handler.NewAuthHandler(sessionSvc),
|
||||
},
|
||||
middleware.Auth(store.Users()),
|
||||
middleware.BearerAuth(sessionSvc),
|
||||
)
|
||||
|
||||
srv := &http.Server{
|
||||
@@ -55,17 +81,10 @@ func main() {
|
||||
<-quit
|
||||
log.Println("Получен сигнал завершения, останавливаем сервер...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Fatalf("Ошибка при остановке: %v", err)
|
||||
}
|
||||
log.Println("Сервер остановлен")
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user