-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
113 lines (86 loc) · 2.24 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"errors"
)
type book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Quantity int `json:"quantity"`
}
var books = []book{
{ID: "1", Title: "In Search of Lost Time", Author: "Marcel Proust", Quantity: 2},
{ID: "2", Title: "The Great Gatsby", Author: "F. Scott Fitzgerald", Quantity: 5},
{ID: "3", Title: "War and Peace", Author: "Leo Tolstoy", Quantity: 6},
}
func getBooks(c *gin.Context){
c.IndentedJSON(http.StatusOK, books)
}
func bookById(c *gin.Context){
id := c.Param("id")
book, err := getBookById(id)
if err != nil {
c.IndentedJSON(http.StatusNotFound,gin.H{"message":"Book not found."})
return
}
c.IndentedJSON(http.StatusOK, book)
}
func checkoutBook(c *gin.Context){
id, ok := c.GetQuery("id")
if !ok { // 修正: err を ok に変更
c.IndentedJSON(http.StatusBadRequest,gin.H{"message":"Missing id query parametor"})
return
}
book,err := getBookById(id)
if err != nil{
c.IndentedJSON(http.StatusBadRequest,gin.H{"message":"Book Not Found."})
return
}
if book.Quantity == 0 {
c.IndentedJSON(http.StatusNotFound,gin.H{"message":"Book Not available."})
return
}
book.Quantity -= 1
c.IndentedJSON(http.StatusOK, book)
}
func returnBook(c *gin.Context){
id, ok := c.GetQuery("id")
if !ok { // 修正: err を ok に変更
c.IndentedJSON(http.StatusBadRequest,gin.H{"message":"Missing id query parametor"})
return
}
book,err := getBookById(id)
if err != nil{
c.IndentedJSON(http.StatusBadRequest,gin.H{"message":"Book Not Found."})
return
}
book.Quantity += 1
c.IndentedJSON(http.StatusOK,book)
}
func getBookById(id string)(*book,error){
for i,b := range books {
if b.ID == id {
return &books[i],nil
}
}
return nil, errors.New("book not found")
}
func createBook(c *gin.Context) {
var newBook book
if err := c.BindJSON(&newBook); err != nil{
return
}
books = append(books,newBook)
c.IndentedJSON(http.StatusCreated,newBook)
}
func main(){
router := gin.Default()
router.GET("/books", getBooks)
router.GET("/books/:id",bookById)
router.POST("/books", createBook)
router.PATCH("/checkout", checkoutBook)
router.PATCH("/return", returnBook)
router.Run("localhost:8080")
}