-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
109 lines (90 loc) · 2.17 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
package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/rs/xid"
"net/http"
"os"
"time"
)
var recipes []Recipe
func init() {
recipes = make([]Recipe, 0)
file, _ := os.ReadFile("recipe.json")
_ = json.Unmarshal(file, &recipes)
}
func main() {
router := gin.Default()
fmt.Println("serving on http://localhost:8080/")
router.GET("/", IndexHandler)
router.POST("/recipes", NewRecipeHandler)
router.GET("/recipes", ListRecipeHandler)
router.PUT("/recipes/:id", UpdateRecipeHandler)
router.DELETE("/recipes/:id", DeleteRecipeHandler)
router.Run()
}
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"`
}
func IndexHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "hello world",
})
}
func ListRecipeHandler(c *gin.Context) {
c.JSON(http.StatusOK, recipes)
}
func NewRecipeHandler(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()
recipes = append(recipes, recipe)
c.JSON(http.StatusOK, recipe)
}
func UpdateRecipeHandler(c *gin.Context) {
var recipe Recipe
if err := c.ShouldBindJSON(&recipe); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
id := c.Param("id")
index := -1
for i := 0; i < len(recipes); i++ {
if recipes[i].ID == id {
index = i
}
}
if index == -1 {
c.JSON(http.StatusNotFound, gin.H{"error": "Recipe not found"})
return
}
recipe.ID = id
recipes[index] = recipe
c.JSON(http.StatusOK, recipe)
}
func DeleteRecipeHandler(c *gin.Context) {
id := c.Param("id")
index := -1
for i := 0; i < len(recipes); i++ {
if recipes[i].ID == id {
index = i
}
}
if index == -1 {
c.JSON(http.StatusNotFound, gin.H{"error": "Recipe not found"})
return
}
recipes = append(recipes[:index], recipes[index+1:]...)
c.JSON(http.StatusOK, gin.H{"message": "Recipe has been deleted"})
}