-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusers.go
78 lines (67 loc) · 1.61 KB
/
users.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
package handlers
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var users = []User{
{ID: 1, Name: "Radha"},
{ID: 2, Name: "Krishna"},
}
func GetUsers(c *gin.Context) {
c.JSON(http.StatusOK, users)
}
func GetUser(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
for _, user := range users {
if user.ID == id {
c.JSON(http.StatusOK, user)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
}
var lastID = 2 // keep track of last used ID
func CreateUser(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
lastID++ // increment last used ID
user.ID = lastID // assign new ID to user
users = append(users, user)
c.JSON(http.StatusOK, user)
}
func UpdateUser(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var updateUser User
if err := c.ShouldBindJSON(&updateUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
for i, user := range users {
if user.ID == id {
updateUser.ID = id // set the id of updateUser
users[i] = updateUser
c.JSON(http.StatusOK, updateUser)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
}
func DeleteUser(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
for i, user := range users {
if user.ID == id {
users = append(users[:i], users[i+1:]...)
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
return
}
}
c.JSON(http.StatusNotFound, gin.H{"status": "not found"})
}