Files
asset_helper/backend/api/handlers/user.go
2026-04-08 21:50:48 +08:00

155 lines
2.9 KiB
Go

package handlers
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// UserRequest 用户请求
type UserRequest struct {
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email"`
}
// UserResponse 用户响应
type UserResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ListUsers 获取用户列表
func (h *Handler) ListUsers(c *gin.Context) {
// TODO: 实现从数据库获取用户列表
users := []UserResponse{
{
ID: 1,
Name: "张三",
Email: "zhangsan@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
{
ID: 2,
Name: "李四",
Email: "lisi@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": users,
})
}
// GetUser 获取单个用户
func (h *Handler) GetUser(c *gin.Context) {
id := c.Param("id")
// TODO: 实现从数据库获取用户
// 尝试从缓存获取
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cached, err := h.cfg.Redis.Get(ctx, "user:"+id).Result()
if err == nil && cached != "" {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": cached,
"cached": true,
})
return
}
// 模拟从数据库获取
user := UserResponse{
ID: 1,
Name: "张三",
Email: "zhangsan@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": user,
})
}
// CreateUser 创建用户
func (h *Handler) CreateUser(c *gin.Context) {
var req UserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": err.Error(),
})
return
}
// TODO: 实现保存到数据库
user := UserResponse{
ID: 1,
Name: req.Name,
Email: req.Email,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
c.JSON(http.StatusCreated, gin.H{
"code": 0,
"data": user,
})
}
// UpdateUser 更新用户
func (h *Handler) UpdateUser(c *gin.Context) {
id := c.Param("id")
var req UserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": err.Error(),
})
return
}
// TODO: 实现更新数据库
_ = id
user := UserResponse{
ID: 1,
Name: req.Name,
Email: req.Email,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": user,
})
}
// DeleteUser 删除用户
func (h *Handler) DeleteUser(c *gin.Context) {
id := c.Param("id")
// TODO: 实现从数据库删除
_ = id
c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "用户已删除",
})
}