package link import ( "encoding/json" "github.com/jackc/pgx/v4/pgxpool" "github.com/labstack/echo/v4" "net/http" ) func creationHandler(c echo.Context, pool *pgxpool.Pool) error { var model CreationModel if err := json.NewDecoder(c.Request().Body).Decode(&model); err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid data format.") } entity, err := model.MapModelToEntity() if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid URL.") } rep := PgRepository{pool: pool} link, err := rep.FindById(entity.Id) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError) } if link != nil { return echo.NewHTTPError(http.StatusBadRequest, "Link with given ID already exists.") } if err = rep.Save(entity); err != nil { return echo.NewHTTPError(http.StatusInternalServerError) } 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 AddHandlers(s *echo.Echo, pool *pgxpool.Pool) { s.POST("", func(ctx echo.Context) error { return creationHandler(ctx, pool) }) s.GET("/:id", func(ctx echo.Context) error { return redirectHandler(ctx, pool) }) }