package server import ( "context" "errors" "fmt" "net/http" "os" "os/signal" "time" "github.com/a-h/templ" "github.com/labstack/echo/v4" "gorm.io/gorm" "github.com/rjNemo/rentease/internal/domains/booking" "github.com/rjNemo/rentease/internal/pdf" ) type Server struct { Router *echo.Echo db *gorm.DB bs *booking.Service ps *pdf.PdfService addr string } func New(db *gorm.DB) *Server { return &Server{ Router: echo.New(), db: db, bs: booking.NewService(db), ps: pdf.NewPdfService(), addr: fmt.Sprintf("0.0.0.0:%s", os.Getenv("PORT")), } } func (s Server) Start() { go func() { if err := s.Router.Start(s.addr); err != nil && !errors.Is(err, http.ErrServerClosed) { s.Router.Logger.Fatal("shutting down the server") } }() quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt) <-quit ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := s.Router.Shutdown(ctx); err != nil { s.Router.Logger.Fatal(err) } } func renderTempl(c echo.Context, status int, t templ.Component) error { c.Response().Writer.WriteHeader(status) err := t.Render(context.Background(), c.Response().Writer) if err != nil { return c.String(http.StatusInternalServerError, "failed to render response template") } return nil } func (s Server) renderTempl(c echo.Context, status int, t templ.Component) error { c.Response().Writer.WriteHeader(status) err := t.Render(context.Background(), c.Response().Writer) if err != nil { return c.String(http.StatusInternalServerError, "failed to render response template") } return nil } func (s Server) customHTTPErrorHandler(err error, c echo.Context) { code := http.StatusInternalServerError var he *echo.HTTPError if errors.As(err, &he) { code = he.Code } s.Router.Logger.Error(err) errorPage := fmt.Sprintf("assets/html/HTTP%d.html", code) if err := c.File(errorPage); err != nil { c.Logger().Error(err) } }