Add existing codebase

This commit is contained in:
Andrey Chervyakov 2021-03-13 01:43:08 +06:00
commit c23a68347b
16 changed files with 807 additions and 0 deletions

63
link/handlers.go Normal file
View file

@ -0,0 +1,63 @@
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)
})
}