package link import ( . "cgnolink/err" "encoding/json" "github.com/jackc/pgx/v4/pgxpool" "github.com/labstack/echo/v4" "net/http" "strconv" ) func redirectHandler(c echo.Context, pool *pgxpool.Pool) error { linkId := c.Param("id") serv := PgService{rep: PgRepository{pool: pool}} link, err := serv.GetById(linkId) if err != nil { return MapErrToHTTPErr(err) } 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 { return echo.NewHTTPError(http.StatusBadRequest, "Invalid data format.") } entity, err := model.MapModelToEntity() if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid URL.") } serv := PgService{rep: PgRepository{pool: pool}} if err = serv.Create(entity); err != nil { return MapErrToHTTPErr(err) } return c.NoContent(http.StatusCreated) } func retrievalByIdHandler(c echo.Context, pool *pgxpool.Pool) error { linkId := c.Param("id") serv := PgService{rep: PgRepository{pool: pool}} l, err := serv.GetById(linkId) if err != nil { return MapErrToHTTPErr(err) } return c.JSON(http.StatusOK, MapEntityToModel(l)) } func allRetrievalHandler(c echo.Context, pool *pgxpool.Pool) error { limit := 20 if v := c.QueryParam("limit"); v != "" { num, err := strconv.Atoi(v) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid limit value.") } limit = num } offset := 0 if v := c.QueryParam("offset"); v != "" { num, err := strconv.Atoi(v) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, "Invalid offset value.") } offset = num } serv := PgService{rep: PgRepository{pool: pool}} links, err := serv.GetAll(limit, offset) if err != nil { return MapErrToHTTPErr(err) } models := make([]ResourceModel, len(links)) for i, v := range links { models[i] = MapEntityToModel(v) } return c.JSON(http.StatusOK, models) } func removalHandler(c echo.Context, pool *pgxpool.Pool) error { linkId := c.Param("id") serv := PgService{rep: PgRepository{pool: pool}} if err := serv.DeleteById(linkId); err != nil { return MapErrToHTTPErr(err) } return c.NoContent(http.StatusNoContent) } func AddHandlers(s *echo.Echo, pool *pgxpool.Pool) { gr := s.Group("/links") gr.POST("", func(ctx echo.Context) error { return creationHandler(ctx, pool) }) gr.GET("", func(ctx echo.Context) error { return allRetrievalHandler(ctx, pool) }) gr.GET("/:id", func(ctx echo.Context) error { return retrievalByIdHandler(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) }) }