-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (60 loc) · 1.24 KB
/
main.go
File metadata and controls
82 lines (60 loc) · 1.24 KB
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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"github.com/gin-gonic/gin"
)
func loadJSON() []book {
file, err := os.Open("books.json")
if err != nil {
fmt.Println(err.Error())
}
defer file.Close()
byteValue, _ := io.ReadAll(file)
var books []book
json.Unmarshal(byteValue, &books)
return books
}
var books = loadJSON()
func searchBookID(id int) (*book, error) {
for i, b := range books {
if b.ID == id {
return &books[i], nil
}
}
return nil, errors.New("Book not found!")
}
func getAllBooks(c *gin.Context) {
c.IndentedJSON(http.StatusOK, books)
}
func addBook(c *gin.Context) {
var newBook book
if err := c.BindJSON(&newBook); err != nil {
return
}
books = append(books, newBook)
c.IndentedJSON(http.StatusCreated, newBook)
createJSON(books)
}
func getBookByID(c *gin.Context) {
id := c.Param("id")
i, err := strconv.Atoi(id)
book, err := searchBookID(i)
if err != nil {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book Not Found!"})
return
}
c.IndentedJSON(http.StatusOK, book)
}
func main() {
router := gin.Default()
router.GET("/books", getAllBooks)
router.POST("/add", addBook)
router.GET("/books/:id", getBookByID)
router.Run("localhost:8080")
}