-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (45 loc) · 985 Bytes
/
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
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.GET("/books", listBooksHandler)
r.POST("/books", createBookHandler)
r.DELETE("/books/:id", deleteBookHandler)
r.Run()
}
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
var books = []Book{
{ID: "1", Title: "title1", Author: "author1"},
{ID: "2", Title: "title2", Author: "author2"},
}
func listBooksHandler(c *gin.Context) {
c.JSON(http.StatusOK, books)
}
func createBookHandler(c *gin.Context) {
var book Book
if err := c.ShouldBindJSON(&book); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
books = append(books, book)
c.JSON(http.StatusCreated, book)
}
func deleteBookHandler(c *gin.Context) {
id := c.Param("id")
for i, a := range books {
if a.ID == id {
books = append(books[:i], books[i+1:]...)
break
}
}
c.Status(http.StatusNoContent)
}