@@ -3,6 +3,7 @@ package handler
33import (
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+
4962func (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+ }
0 commit comments