You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.3 KiB
94 lines
2.3 KiB
package http
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"auroragolang/internal/domain/model"
|
|
"auroragolang/internal/usecase"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
service *usecase.UserService
|
|
}
|
|
|
|
type ErrorResponse struct {
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func NewUserHandler(service *usecase.UserService) *UserHandler {
|
|
return &UserHandler{service: service}
|
|
}
|
|
|
|
// ListUsers godoc
|
|
// @Summary 获取用户列表
|
|
// @Description 返回所有用户
|
|
// @Tags users
|
|
// @Produce json
|
|
// @Success 200 {array} model.User
|
|
// @Failure 500 {object} ErrorResponse
|
|
// @Router /api/v1/users [get]
|
|
func (h *UserHandler) ListUsers(c *gin.Context) {
|
|
users, err := h.service.ListUsers()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, users)
|
|
}
|
|
|
|
// GetUser godoc
|
|
// @Summary 获取指定用户
|
|
// @Description 根据用户 ID 获取详情
|
|
// @Tags users
|
|
// @Produce json
|
|
// @Param id path int true "用户 ID"
|
|
// @Success 200 {object} model.User
|
|
// @Failure 400 {object} ErrorResponse
|
|
// @Failure 404 {object} ErrorResponse
|
|
// @Router /api/v1/users/{id} [get]
|
|
func (h *UserHandler) GetUser(c *gin.Context) {
|
|
idParam := c.Param("id")
|
|
id, err := strconv.Atoi(idParam)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
|
|
return
|
|
}
|
|
|
|
user, err := h.service.GetUser(uint(id))
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, user)
|
|
}
|
|
|
|
// CreateUser godoc
|
|
// @Summary 创建用户
|
|
// @Description 创建新的用户记录
|
|
// @Tags users
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param user body model.User true "用户数据"
|
|
// @Success 201 {object} model.User
|
|
// @Failure 400 {object} ErrorResponse
|
|
// @Failure 500 {object} ErrorResponse
|
|
// @Router /api/v1/users [post]
|
|
func (h *UserHandler) CreateUser(c *gin.Context) {
|
|
var payload model.User
|
|
if err := c.ShouldBindJSON(&payload); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
if err := h.service.CreateUser(&payload); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, payload)
|
|
}
|
|
|
|
|