/
book.go
74 lines (60 loc) · 1.71 KB
/
book.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package handler
import (
"net/http"
"strconv"
"github.com/go-playground/validator"
"github.com/labstack/echo"
"github.com/moritamori/echo-testing/model"
"github.com/moritamori/echo-testing/repo"
)
type BookHandler struct {
bookRepo repo.BookRepo
}
type resultLists struct {
Books []model.Book `json:"Books"`
}
func NewBookHandler(br repo.BookRepo) *BookHandler {
return &BookHandler{br}
}
func (bh *BookHandler) GetIndex(c echo.Context) error {
bks, err := bh.bookRepo.FindAll()
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
rl := &resultLists{Books: bks}
return c.JSON(http.StatusOK, rl)
}
func (bh *BookHandler) GetDetail(c echo.Context) error {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
b, err := bh.bookRepo.FindByID(id)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, b)
}
func (bh *BookHandler) Post(c echo.Context) error {
t := c.FormValue("title")
a := c.FormValue("author")
b := model.Book{Title: t, Author: a}
if err := validator.New().Struct(b); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
if err := bh.bookRepo.Create(&b); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, b)
}
func (bh *BookHandler) Put(c echo.Context) error {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
b, _ := bh.bookRepo.FindByID(id)
t := c.FormValue("title")
a := c.FormValue("author")
b = model.Book{Title: t, Author: a}
if err := validator.New().Struct(b); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
if err := bh.bookRepo.Save(&b); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, b)
}