refactor: use router constructor instead of struct

This commit is contained in:
Guz
2026-02-21 17:10:44 -03:00
parent dc32843aad
commit 07d4dba8ad
2 changed files with 12 additions and 24 deletions

View File

@@ -45,12 +45,8 @@ func main() {
}
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", "", 8080),
Handler: &router{
assets: as,
templates: ts,
logger: log,
},
Addr: fmt.Sprintf("%s:%d", "", 8080),
Handler: newRouter(as, ts, log),
}
c, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)

View File

@@ -11,13 +11,7 @@ import (
"code.capytal.cc/loreddev/x/xtemplate"
)
type router struct {
assets http.Handler
templates xtemplate.Templater
logger *slog.Logger
}
func (ctrl *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func newRouter(assets http.Handler, templates xtemplate.Templater, logger *slog.Logger) http.Handler {
mux := multiplexer.New()
mux = multiplexer.WithPatternRules(mux,
multiplexer.EnsureMethod(),
@@ -25,19 +19,17 @@ func (ctrl *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
multiplexer.EnsureTrailingSlash(),
)
router := smalltrip.NewRouter(smalltrip.WithMultiplexer(mux), smalltrip.WithLogger(ctrl.logger))
router := smalltrip.NewRouter(smalltrip.WithMultiplexer(mux), smalltrip.WithLogger(logger))
router.Use(problem.Middleware(problem.DefaultHandler))
router.Use(middleware.Logger(ctrl.logger))
router.Use(middleware.Logger(logger))
router.Handle("GET /assets/{file...}", ctrl.assets)
router.HandleFunc("GET /{$}", ctrl.landing)
router.Handle("GET /assets/{file...}", assets)
router.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
if err := templates.ExecuteTemplate(w, "landing", nil); err != nil {
problem.NewInternalServerError(err).ServeHTTP(w, r)
}
})
router.ServeHTTP(w, r)
}
func (ctrl *router) landing(w http.ResponseWriter, r *http.Request) {
if err := ctrl.templates.ExecuteTemplate(w, "landing", nil); err != nil {
problem.NewInternalServerError(err).ServeHTTP(w, r)
}
return router
}