-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
106 lines (84 loc) · 1.61 KB
/
Copy pathmain.go
File metadata and controls
106 lines (84 loc) · 1.61 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"log"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type user struct {
ID string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
var users []user
func main() {
r := gin.Default()
userRoutes := r.Group("/users")
{
userRoutes.GET("/", getUsers)
userRoutes.POST("/", CreateUser)
userRoutes.PUT("/:id", EditUser)
userRoutes.DELETE("/:id", DeleteUser)
}
if err := r.Run(":5000"); err != nil {
log.Fatal(err.Error())
}
}
func getUsers(c *gin.Context) {
c.JSON(200, users)
}
func CreateUser(c *gin.Context) {
var reqBody user
if err := c.ShouldBindJSON(&reqBody); err != nil {
c.JSON(422, gin.H{
"error": true,
"message": "invalid request body",
})
return
}
reqBody.ID = uuid.New().String()
users = append(users, reqBody)
c.JSON(200, gin.H{
"error": false,
})
}
func EditUser(c *gin.Context) {
id := c.Param("id")
var reqBody user
if err := c.ShouldBindJSON(&reqBody); err != nil {
c.JSON(422, gin.H{
"error": true,
"message": "invalid request body",
})
return
}
for i, u := range users {
if u.ID == id {
users[i].Name = reqBody.Name
users[i].Age = reqBody.Age
c.JSON(200, gin.H{
"error": false,
})
return
}
}
c.JSON(404, gin.H{
"error": true,
"message": "could not find user with supplied id",
})
}
func DeleteUser(c *gin.Context) {
id := c.Param("id")
for i, u := range users {
if u.ID == id {
users = append(users[:i], users[i+1:]...)
c.JSON(200, gin.H{
"error": false,
})
return
}
}
c.JSON(404, gin.H{
"error": true,
"message": "Id not found",
})
}