用gin写一个增删改查
时间: 2024-04-27 09:25:37 浏览: 12
好的,以下是使用 Gin 框架编写一个简单的增删改查的示例代码:
```go
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
var userList []User
func main() {
r := gin.Default()
// 查询用户列表
r.GET("/users", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"data": userList,
})
})
// 根据 ID 查询用户
r.GET("/users/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid user ID",
})
return
}
for _, user := range userList {
if user.ID == id {
c.JSON(http.StatusOK, gin.H{
"data": user,
})
return
}
}
c.JSON(http.StatusNotFound, gin.H{
"message": "User not found",
})
})
// 新增用户
r.POST("/users", func(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid user data",
})
return
}
user.ID = len(userList) + 1
userList = append(userList, user)
c.JSON(http.StatusOK, gin.H{
"message": "User created successfully",
"data": user,
})
})
// 更新用户
r.PUT("/users/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid user ID",
})
return
}
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid user data",
})
return
}
for i, oldUser := range userList {
if oldUser.ID == id {
user.ID = id
userList[i] = user
c.JSON(http.StatusOK, gin.H{
"message": "User updated successfully",
"data": user,
})
return
}
}
c.JSON(http.StatusNotFound, gin.H{
"message": "User not found",
})
})
// 删除用户
r.DELETE("/users/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid user ID",
})
return
}
for i, user := range userList {
if user.ID == id {
userList = append(userList[:i], userList[i+1:]...)
c.JSON(http.StatusOK, gin.H{
"message": "User deleted successfully",
})
return
}
}
c.JSON(http.StatusNotFound, gin.H{
"message": "User not found",
})
})
r.Run() // 启动 HTTP 服务
}
```
这是一个非常简单的示例,用于演示如何使用 Gin 框架实现增删改查功能。可以通过访问以下 URL 来测试:
- 查询用户列表:GET http://localhost:8080/users
- 根据 ID 查询用户:GET http://localhost:8080/users/:id
- 新增用户:POST http://localhost:8080/users
- 更新用户:PUT http://localhost:8080/users/:id
- 删除用户:DELETE http://localhost:8080/users/:id
其中,`:id` 代表用户的 ID,需要替换成实际的用户 ID。在请求中,需要提供 JSON 格式的请求体来传递用户数据。可以使用 Postman 等工具来测试这些 API。