link-go/link/handlers.go
2021-03-13 17:18:23 +06:00

82 lines
1.9 KiB
Go

package link
import (
"encoding/json"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/labstack/echo/v4"
"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 {
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 removalHandler(c echo.Context, pool *pgxpool.Pool) error {
linkId := c.Param("id")
rep := PgRepository{pool: pool}
if err := rep.DeleteById(linkId); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError)
}
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.DELETE("/:id", func(ctx echo.Context) error {
return removalHandler(ctx, pool)
})
s.GET("/:id", func(ctx echo.Context) error {
return redirectHandler(ctx, pool)
})
}