forked from mtusi2026/mtusi2026lab2
реализован уровень 3
This commit is contained in:
+100
-39
@@ -10,86 +10,147 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/config"
|
||||
"mtusi2026lab2/internal/database"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/handlers"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := os.Getenv("HTTP_ADDR")
|
||||
if addr == "" {
|
||||
port := os.Getenv("PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
addr = "0.0.0.0:" + port
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] Invalid configuration: %v", err)
|
||||
}
|
||||
|
||||
memStore := store.NewMemoryStore()
|
||||
h := handlers.NewHandler(memStore)
|
||||
startupContext, startupCancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
cfg.DatabaseConnectTimeout,
|
||||
)
|
||||
|
||||
databasePool, err := database.Open(startupContext, cfg)
|
||||
startupCancel()
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
|
||||
}
|
||||
defer databasePool.Close()
|
||||
|
||||
postgresStore := store.NewPostgreSQLStore(
|
||||
databasePool,
|
||||
cfg.DatabaseQueryTimeout,
|
||||
)
|
||||
|
||||
handler := handlers.NewHandler(
|
||||
postgresStore,
|
||||
handlers.WithReadiness(
|
||||
databasePool,
|
||||
cfg.ReadinessTimeout,
|
||||
),
|
||||
handlers.WithSessionTTL(cfg.SessionTTL),
|
||||
)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
//паблик систем ручки
|
||||
mux.HandleFunc("GET /health/live", h.HealthLive)
|
||||
mux.HandleFunc("GET /health/ready", h.HealthReady)
|
||||
mux.HandleFunc("GET /health/live", handler.HealthLive)
|
||||
mux.HandleFunc("GET /health/ready", handler.HealthReady)
|
||||
|
||||
// паблик рег юзера
|
||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/auth/sessions",
|
||||
handler.CreateSession,
|
||||
)
|
||||
|
||||
//защищенные через мидлварьки
|
||||
mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(memStore, h.GetMe))
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
|
||||
mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(memStore, h.CreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(memStore, h.ListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(memStore, h.GetChat))
|
||||
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return middleware.RequireAuth(postgresStore, next)
|
||||
}
|
||||
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.CreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.GetMessages))
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
requireAuth(handler.GetMe),
|
||||
)
|
||||
|
||||
mux.HandleFunc(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
requireAuth(handler.DeleteCurrentSession),
|
||||
)
|
||||
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats",
|
||||
requireAuth(handler.CreateChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats",
|
||||
requireAuth(handler.ListChats),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
requireAuth(handler.GetChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
requireAuth(handler.CreateMessage),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
requireAuth(handler.GetMessages),
|
||||
)
|
||||
|
||||
//конвейер
|
||||
var rootHandler http.Handler = mux
|
||||
rootHandler = middleware.Recovery(rootHandler)
|
||||
rootHandler = middleware.Logger(rootHandler)
|
||||
rootHandler = middleware.RequestID(rootHandler)
|
||||
|
||||
//конф сервака
|
||||
server := &http.Server{
|
||||
Addr: addr,
|
||||
Addr: cfg.HTTPAddress(),
|
||||
Handler: rootHandler,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
//серв в рутине запущен
|
||||
serverErrors := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Printf("[INFO] Server starting on %s", addr)
|
||||
log.Printf("[INFO] Server starting on %s", server.Addr)
|
||||
serverErrors <- server.ListenAndServe()
|
||||
}()
|
||||
|
||||
shutdown := make(chan os.Signal, 1)
|
||||
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
|
||||
shutdownSignals := make(chan os.Signal, 1)
|
||||
signal.Notify(
|
||||
shutdownSignals,
|
||||
os.Interrupt,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
defer signal.Stop(shutdownSignals)
|
||||
|
||||
//падение/сигнал на выкл
|
||||
select {
|
||||
case err := <-serverErrors:
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("[FATAL] Server crashed: %v", err)
|
||||
case serverError := <-serverErrors:
|
||||
if !errors.Is(serverError, http.ErrServerClosed) {
|
||||
log.Fatalf("[FATAL] Server crashed: %v", serverError)
|
||||
}
|
||||
|
||||
case sig := <-shutdown:
|
||||
log.Printf("[INFO] Signal %v received. Starting graceful shutdown...", sig)
|
||||
case signalValue := <-shutdownSignals:
|
||||
log.Printf(
|
||||
"[INFO] Signal %v received. Starting graceful shutdown...",
|
||||
signalValue,
|
||||
)
|
||||
|
||||
// завершение не более чем за 10 секунд
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
shutdownContext, shutdownCancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
cfg.ShutdownTimeout,
|
||||
)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
log.Printf("[WARN] Graceful shutdown failed: %v. Forcing close.", err)
|
||||
if err := server.Shutdown(shutdownContext); err != nil {
|
||||
log.Printf(
|
||||
"[WARN] Graceful shutdown failed: %v. Forcing close.",
|
||||
err,
|
||||
)
|
||||
_ = server.Close()
|
||||
}
|
||||
|
||||
log.Println("[INFO] Server stopped gracefully.")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user