/
get_post.go
52 lines (40 loc) · 1.06 KB
/
get_post.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package posts
import (
"errors"
"fmt"
"net/http"
"strconv"
"github.com/ekkinox/fx-template/internal/repository"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
type GetPostHandler struct {
repository *repository.PostRepository
}
func NewGetPostHandler(repository *repository.PostRepository) *GetPostHandler {
return &GetPostHandler{
repository: repository,
}
}
func (h *GetPostHandler) Handle() echo.HandlerFunc {
return func(c echo.Context) error {
c.Logger().Info("in get post handler")
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
msg := fmt.Sprintf("invalid id: %v", err)
c.Logger().Error(msg)
return echo.NewHTTPError(http.StatusBadRequest, msg)
}
post, err := h.repository.Find(c.Request().Context(), id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
msg := fmt.Sprintf("cannot get post with id %d: %v", id, err)
c.Logger().Error(msg)
return echo.NewHTTPError(http.StatusNotFound, msg)
}
c.Logger().Errorf("cannot get post: %v", err)
return err
}
return c.JSON(http.StatusOK, post)
}
}