From 750899c93f4015e1b400516b32582f7a4c2c1681 Mon Sep 17 00:00:00 2001 From: Andrey Chervyakov Date: Sat, 13 Mar 2021 17:18:23 +0600 Subject: [PATCH] Extract links manipulation endpoints in separate resource --- link/handlers.go | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/link/handlers.go b/link/handlers.go index da24868..a07cdbe 100644 --- a/link/handlers.go +++ b/link/handlers.go @@ -7,6 +7,23 @@ import ( "net/http" ) +func redirectHandler(c echo.Context, pool *pgxpool.Pool) error { + linkId := c.Param("id") + + rep := PgRepository{pool: pool} + + link, err := rep.FindById(linkId) + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError) + } + + if link == nil { + return echo.NewHTTPError(http.StatusNotFound, "Link with given ID was not found.") + } + + return c.Redirect(http.StatusSeeOther, link.RedirectURL.String()) +} + func creationHandler(c echo.Context, pool *pgxpool.Pool) error { var model CreationModel if err := json.NewDecoder(c.Request().Body).Decode(&model); err != nil { @@ -36,23 +53,6 @@ func creationHandler(c echo.Context, pool *pgxpool.Pool) error { return c.NoContent(http.StatusCreated) } -func redirectHandler(c echo.Context, pool *pgxpool.Pool) error { - linkId := c.Param("id") - - rep := PgRepository{pool: pool} - - link, err := rep.FindById(linkId) - if err != nil { - return echo.NewHTTPError(http.StatusInternalServerError) - } - - if link == nil { - return echo.NewHTTPError(http.StatusNotFound, "Link with given ID was not found.") - } - - return c.Redirect(http.StatusSeeOther, link.RedirectURL.String()) -} - func removalHandler(c echo.Context, pool *pgxpool.Pool) error { linkId := c.Param("id") @@ -66,15 +66,17 @@ func removalHandler(c echo.Context, pool *pgxpool.Pool) error { } func AddHandlers(s *echo.Echo, pool *pgxpool.Pool) { - s.POST("", func(ctx echo.Context) error { + gr := s.Group("/links") + + gr.POST("", func(ctx echo.Context) error { return creationHandler(ctx, pool) }) + gr.DELETE("/:id", func(ctx echo.Context) error { + return removalHandler(ctx, pool) + }) + s.GET("/:id", func(ctx echo.Context) error { return redirectHandler(ctx, pool) }) - - s.DELETE("/:id", func(ctx echo.Context) error { - return removalHandler(ctx, pool) - }) }