-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
99 lines (79 loc) · 2.2 KB
/
router.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
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func setupRouter() *gin.Engine {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})
// Create user
r.POST("/user", func(c *gin.Context) {
var json struct {
Name string `json:"name" binding:"required"`
Value string `json:"value" binding:"required"`
}
if err := c.BindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := createUser(json.Name, json.Value); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// Get user by ID
r.GET("/user/:id", func(c *gin.Context) {
id := c.Param("id")
userId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
return
}
user, err := getUserByID(uint(userId))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
c.JSON(http.StatusOK, gin.H{"user": user})
})
// Update user value by ID
r.PUT("/user/:id", func(c *gin.Context) {
id := c.Param("id")
userId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
return
}
var json struct {
Value string `json:"value" binding:"required"`
}
if err := c.BindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := updateUserValue(uint(userId), json.Value); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// Delete user by ID
r.DELETE("/user/:id", func(c *gin.Context) {
id := c.Param("id")
userId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
return
}
if err := deleteUser(uint(userId)); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete user"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
return r
}