-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
126 lines (109 loc) · 2.45 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
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/xid"
)
type Recipe struct {
ID string `json:"id"`
Name string `json:"name"`
Tags []string `json:"tags"`
Ingredients []string `json:"ingredients"`
Instructions []string `json:"instructions"`
PublishedAt time.Time `json:"publishedAt"`
}
var recipesDB []Recipe
func init() {
recipesDB = make([]Recipe, 0)
fileBytes, err := os.ReadFile("recipes.json")
if err != nil {
fmt.Fprintln(os.Stderr, "An error occurred:", err)
return
}
_ = json.Unmarshal(fileBytes, &recipesDB)
}
func IndexHandler(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hosting recipes app",
})
}
func GetRecipesHandler(c *gin.Context) {
c.JSON(http.StatusOK, recipesDB)
}
func PostRecipeHandler(c *gin.Context) {
var recipe Recipe
if err := c.ShouldBindJSON(&recipe); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
recipe.ID = xid.New().String()
recipe.PublishedAt = time.Now()
recipesDB = append(recipesDB, recipe)
c.JSON(http.StatusOK, recipe)
}
func PutRecipesHandler(c *gin.Context) {
id := c.Param("id")
var recipe Recipe
if err := c.ShouldBindJSON(&recipe); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
index := -1
for i := 0; i < len(recipesDB); i++ {
if recipesDB[i].ID == id {
index = i
}
}
if index == -1 {
c.JSON(http.StatusNotFound, gin.H{
"error": "Recipe not found",
})
return
}
recipe.ID = recipesDB[index].ID
recipe.PublishedAt = recipesDB[index].PublishedAt
c.JSON(http.StatusOK, recipe)
}
func DeleteRecipesHandler(c *gin.Context) {
id := c.Param("id")
var recipe Recipe
if err := c.ShouldBindJSON(&recipe); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
index := -1
for i := 0; i < len(recipesDB); i++ {
if recipesDB[i].ID == id {
index = i
}
}
if index == -1 {
c.JSON(http.StatusNotFound, gin.H{
"error": "Recipe not found",
})
return
}
recipesDB = append(recipesDB[:index], recipesDB[index+1:]...)
c.JSON(http.StatusOK, gin.H{
"message": "Deleted recipe with id: " + id,
})
}
func main() {
router := gin.Default()
router.GET("/", IndexHandler)
router.GET("/recipes", GetRecipesHandler)
router.POST("/recipes", PostRecipeHandler)
router.PUT("/recipes/:id", PutRecipesHandler)
router.DELETE("/recipes/:id", DeleteRecipesHandler)
router.Run()
}