main.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "context"
  4. "log/slog"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. "time"
  10. "cmr-backend/internal/app"
  11. )
  12. func main() {
  13. ctx := context.Background()
  14. cfg, err := app.LoadConfigFromEnv()
  15. if err != nil {
  16. slog.Error("load config failed", "error", err)
  17. os.Exit(1)
  18. }
  19. application, err := app.New(ctx, cfg)
  20. if err != nil {
  21. slog.Error("create app failed", "error", err)
  22. os.Exit(1)
  23. }
  24. defer application.Close()
  25. server := &http.Server{
  26. Addr: cfg.HTTPAddr,
  27. Handler: application.Router(),
  28. ReadHeaderTimeout: 5 * time.Second,
  29. }
  30. go func() {
  31. slog.Info("api server started", "addr", cfg.HTTPAddr)
  32. if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  33. slog.Error("server stopped unexpectedly", "error", err)
  34. os.Exit(1)
  35. }
  36. }()
  37. stop := make(chan os.Signal, 1)
  38. signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
  39. <-stop
  40. shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  41. defer cancel()
  42. if err := server.Shutdown(shutdownCtx); err != nil {
  43. slog.Error("graceful shutdown failed", "error", err)
  44. os.Exit(1)
  45. }
  46. }