-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (78 loc) · 2.1 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
package main
import (
"blogs/model"
"blogs/schema"
"html"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
)
type blogBody struct {
Title string `json:"title"`
Description string `json:"description"`
}
func main() {
model.CreateTable()
app := fiber.New()
app.Use(recover.New())
app.Get("/blogs", func(c *fiber.Ctx) error {
db := model.ConnectDB()
defer model.CloseDB(db)
blogs := []schema.Blog{}
db.Raw("SELECT * FROM blogs").Scan(&blogs)
var status int
if len(blogs) > 0 {
status = fiber.StatusOK
} else {
status = fiber.StatusNoContent
}
return c.Status(status).JSON(&fiber.Map{
"success": true,
"blogs": blogs,
})
})
app.Post("/blog", func(c *fiber.Ctx) error {
db := model.ConnectDB()
defer model.CloseDB(db)
body := blogBody{}
if err := c.BodyParser(&body); err != nil {
panic(err)
}
body.Title = html.EscapeString(body.Title)
body.Description = html.EscapeString(body.Description)
db.Exec("INSERT INTO blogs (title, description) VALUES (?, ?)", body.Title, body.Description)
return c.Status(fiber.StatusCreated).JSON(&fiber.Map{
"success": true,
})
})
app.Put("/blog/:id", func(c *fiber.Ctx) error {
db := model.ConnectDB()
defer model.CloseDB(db)
id, err := c.ParamsInt("id")
if err != nil {
panic(err)
}
var body blogBody
if err := c.BodyParser(&body); err != nil {
panic(err)
}
body.Title = html.EscapeString(body.Title)
body.Description = html.EscapeString(body.Description)
db.Exec("UPDATE blogs SET title=?, description=? WHERE id=?", body.Title, body.Description, id)
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"success": true,
})
})
app.Delete("/blog/:id", func(c *fiber.Ctx) error {
db := model.ConnectDB()
defer model.CloseDB(db)
id, err := c.ParamsInt("id")
if err != nil {
panic(err)
}
db.Exec("DELETE FROM blogs WHERE id=?", id)
return c.Status(fiber.StatusOK).JSON(&fiber.Map{
"success": true,
})
})
app.Listen(":8000")
}