Skip to content

Commit 602c31a

Browse files
committed
Convert Response
1 parent 9e1c6a8 commit 602c31a

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

handler/book.go

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package handler
33
import (
44
"fmt"
55
"net/http"
6+
"strconv"
67

78
"github.com/gin-gonic/gin"
89
"github.com/go-playground/validator/v10"
@@ -29,14 +30,7 @@ func (h *bookHandler) GetBooks(c *gin.Context) {
2930
var booksResponse []book.BookResponse
3031

3132
for _, b := range books {
32-
bookResponse := book.BookResponse{
33-
ID: b.ID,
34-
Title: b.Title,
35-
Price: b.Price,
36-
Description: b.Description,
37-
Rating: b.Rating,
38-
Discount: b.Discount,
39-
}
33+
bookResponse := convertToBookResponse(b)
4034

4135
booksResponse = append(booksResponse, bookResponse)
4236
}
@@ -46,6 +40,25 @@ func (h *bookHandler) GetBooks(c *gin.Context) {
4640
})
4741
}
4842

43+
func (h *bookHandler) GetBook(c *gin.Context) {
44+
idString := c.Param("id")
45+
id, _ := strconv.Atoi(idString)
46+
47+
b, err := h.bookService.FindByID(id)
48+
49+
if err != nil {
50+
c.JSON(http.StatusBadRequest, gin.H{
51+
"errors": err,
52+
})
53+
}
54+
55+
bookResponse := convertToBookResponse(b)
56+
57+
c.JSON(http.StatusOK, gin.H{
58+
"data": bookResponse,
59+
})
60+
}
61+
4962
func (h *bookHandler) PostBooksHandler(c *gin.Context) {
5063
var bookRequest book.BookRequest
5164

@@ -78,3 +91,14 @@ func (h *bookHandler) PostBooksHandler(c *gin.Context) {
7891
"data": book,
7992
})
8093
}
94+
95+
func convertToBookResponse(b book.Book) book.BookResponse {
96+
return book.BookResponse{
97+
ID: b.ID,
98+
Title: b.Title,
99+
Price: b.Price,
100+
Description: b.Description,
101+
Rating: b.Rating,
102+
Discount: b.Discount,
103+
}
104+
}

main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ func main() {
3232

3333
v1 := router.Group("/v1")
3434
v1.GET("/books", bookHandler.GetBooks)
35+
v1.GET("/books/:id", bookHandler.GetBook) // :id akan dapat berubah
3536

3637
v1.POST("/books", bookHandler.PostBooksHandler)
3738
//alur post data

0 commit comments

Comments
 (0)