merch-api/internal/app/handler.go

82 lines
1.4 KiB
Go
Raw Normal View History

2026-02-23 18:34:38 +03:00
package app
import (
"context"
2026-02-23 20:02:53 +03:00
"github.com/gin-gonic/gin"
2026-02-23 18:34:38 +03:00
log "github.com/sirupsen/logrus"
"merch-api/config"
2026-02-23 20:02:53 +03:00
"merch-api/internal/merch"
2026-02-23 19:33:21 +03:00
"merch-api/pkg/router"
"time"
2026-02-23 18:34:38 +03:00
)
type App struct {
2026-02-23 20:02:53 +03:00
cfg config.Config
router *router.Router
modules []Module
2026-02-23 18:34:38 +03:00
}
func New(cfg config.Config) *App {
2026-02-23 20:02:53 +03:00
//providers
2026-02-23 19:33:21 +03:00
r := router.NewRouter(router.Deps{
Host: cfg.Http.Host,
Port: cfg.Http.Port,
Prefix: cfg.Http.Prefix,
GinMode: cfg.Http.GinMode,
})
2026-02-23 20:02:53 +03:00
//modules
var modules []Module
m := merch.New(nil)
modules = append(modules, m)
2026-02-23 19:33:21 +03:00
return &App{
2026-02-23 20:02:53 +03:00
cfg: cfg,
router: r,
modules: modules,
2026-02-23 19:33:21 +03:00
}
2026-02-23 18:34:38 +03:00
}
func (app *App) Run(ctx context.Context) error {
log.Info("Starting application...")
2026-02-23 19:33:21 +03:00
2026-02-23 20:02:53 +03:00
baseGroup := app.router.BaseGroup()
app.collectRoutes(baseGroup)
2026-02-23 19:33:21 +03:00
errCh := make(chan error, 10)
go func() {
if err := app.router.Run(); err != nil {
errCh <- err
}
}()
2026-02-23 18:34:38 +03:00
select {
case <-ctx.Done():
2026-02-23 20:02:53 +03:00
app.shutdown(ctx)
2026-02-23 19:33:21 +03:00
case err := <-errCh:
return err
2026-02-23 18:34:38 +03:00
}
return nil
}
2026-02-23 20:02:53 +03:00
func (app *App) shutdown(ctx context.Context) {
2026-02-23 18:34:38 +03:00
log.Info("Shutting down application...")
2026-02-23 19:33:21 +03:00
shutdownCtx, shutdownCancel := context.WithTimeout(ctx, 15*time.Second)
defer shutdownCancel()
if err := app.router.Shutdown(shutdownCtx); err != nil {
log.Warnf("Error shutting down application: %v", err)
}
log.Info("Application shutdown complete")
2026-02-23 18:34:38 +03:00
}
2026-02-23 20:02:53 +03:00
func (app *App) collectRoutes(group *gin.RouterGroup) {
for _, m := range app.modules {
m.RegisterRoutes(group)
}
}