From 6f3f7db8709510e4905d81d97d34d5cae6ea781d Mon Sep 17 00:00:00 2001 From: huang <1724659546@qq.com> Date: Mon, 8 Sep 2025 12:30:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=8E=A5=E5=8F=A3=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=80=BC=E7=8A=B6=E6=80=81=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/controller/device/device.go | 10 ++++---- internal/controller/operation/operation.go | 25 ++++++++++---------- internal/controller/response.go | 27 ++++++++++++++++++---- internal/controller/user/user.go | 27 +++++++++++++--------- 4 files changed, 55 insertions(+), 34 deletions(-) diff --git a/internal/controller/device/device.go b/internal/controller/device/device.go index 14a12e3..045f80b 100644 --- a/internal/controller/device/device.go +++ b/internal/controller/device/device.go @@ -3,8 +3,6 @@ package device import ( - "net/http" - "git.huangwc.com/pig/pig-farm-controller/internal/api/middleware" "git.huangwc.com/pig/pig-farm-controller/internal/controller" "git.huangwc.com/pig/pig-farm-controller/internal/logs" @@ -49,19 +47,19 @@ func (c *Controller) Switch(ctx *gin.Context) { // 从上下文中获取用户信息 userValue, exists := ctx.Get("user") if !exists { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息") return } user, ok := userValue.(*middleware.AuthUser) if !ok { - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误") return } var req SwitchRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误") return } @@ -78,7 +76,7 @@ func (c *Controller) Switch(ctx *gin.Context) { "设备控制成功", ); err != nil { c.logger.Error("创建设备控制记录失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "设备控制失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "设备控制失败") return } diff --git a/internal/controller/operation/operation.go b/internal/controller/operation/operation.go index a274e7e..715a107 100644 --- a/internal/controller/operation/operation.go +++ b/internal/controller/operation/operation.go @@ -3,7 +3,6 @@ package operation import ( - "net/http" "strconv" "git.huangwc.com/pig/pig-farm-controller/internal/api/middleware" @@ -42,19 +41,19 @@ func (c *Controller) Create(ctx *gin.Context) { // 从上下文中获取用户信息 userValue, exists := ctx.Get("user") if !exists { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息") return } user, ok := userValue.(*middleware.AuthUser) if !ok { - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误") return } var req CreateRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误") return } @@ -70,7 +69,7 @@ func (c *Controller) Create(ctx *gin.Context) { if err := c.operationHistoryRepo.Create(operation); err != nil { c.logger.Error("创建操作历史记录失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "创建操作历史记录失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "创建操作历史记录失败") return } @@ -82,13 +81,13 @@ func (c *Controller) ListByUser(ctx *gin.Context) { // 从上下文中获取用户信息 userValue, exists := ctx.Get("user") if !exists { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息") return } user, ok := userValue.(*middleware.AuthUser) if !ok { - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误") return } @@ -111,7 +110,7 @@ func (c *Controller) ListByUser(ctx *gin.Context) { operations, err := c.operationHistoryRepo.ListByUserID(user.ID, offset, limit) if err != nil { c.logger.Error("获取操作历史记录失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "获取操作历史记录失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "获取操作历史记录失败") return } @@ -123,7 +122,7 @@ func (c *Controller) Get(ctx *gin.Context) { // 获取操作历史记录ID id, err := strconv.ParseUint(ctx.Param("id"), 10, 64) if err != nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "无效的操作历史记录ID") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "无效的操作历史记录ID") return } @@ -131,26 +130,26 @@ func (c *Controller) Get(ctx *gin.Context) { operation, err := c.operationHistoryRepo.FindByID(uint(id)) if err != nil { c.logger.Error("获取操作历史记录失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "获取操作历史记录失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "获取操作历史记录失败") return } // 从上下文中获取用户信息 userValue, exists := ctx.Get("user") if !exists { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息") return } user, ok := userValue.(*middleware.AuthUser) if !ok { - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误") return } // 检查操作历史记录是否属于当前用户 if operation.UserID != user.ID { - controller.SendErrorResponse(ctx, http.StatusForbidden, "无权访问该操作历史记录") + controller.SendErrorResponse(ctx, controller.ForbiddenCode, "无权访问该操作历史记录") return } diff --git a/internal/controller/response.go b/internal/controller/response.go index fd6bdf2..c8fde42 100644 --- a/internal/controller/response.go +++ b/internal/controller/response.go @@ -15,27 +15,46 @@ type APIResponse struct { Data interface{} `json:"data,omitempty"` } +// 自定义状态码常量 +const ( + SuccessCode = 0 // 成功 + InvalidParameterCode = 1001 // 参数无效 + UnauthorizedCode = 1002 // 未授权 + ForbiddenCode = 1003 // 禁止访问 + NotFoundCode = 1004 // 资源未找到 + InternalServerErrorCode = 1005 // 内部服务器错误 +) + // SuccessResponseData 成功响应数据结构体 type SuccessResponseData struct { Message string `json:"message"` Data interface{} `json:"data,omitempty"` } -// sendSuccessResponse 发送成功响应的公共函数 +// SendSuccessResponse 发送成功响应的公共函数 func SendSuccessResponse(ctx *gin.Context, message string, data interface{}) { response := APIResponse{ - Code: http.StatusOK, + Code: SuccessCode, Message: message, Data: data, } ctx.JSON(http.StatusOK, response) } -// sendErrorResponse 发送错误响应的公共函数 +// SendErrorResponse 发送错误响应的公共函数 func SendErrorResponse(ctx *gin.Context, code int, message string) { response := APIResponse{ Code: code, Message: message, } - ctx.JSON(code, response) + ctx.JSON(http.StatusOK, response) +} + +// SendHTTPErrorResponse 发送HTTP错误响应的公共函数 +func SendHTTPErrorResponse(ctx *gin.Context, httpCode int, code int, message string) { + response := APIResponse{ + Code: code, + Message: message, + } + ctx.JSON(httpCode, response) } diff --git a/internal/controller/user/user.go b/internal/controller/user/user.go index e75f372..a708b45 100644 --- a/internal/controller/user/user.go +++ b/internal/controller/user/user.go @@ -8,6 +8,7 @@ import ( "git.huangwc.com/pig/pig-farm-controller/internal/api/middleware" "git.huangwc.com/pig/pig-farm-controller/internal/controller" "git.huangwc.com/pig/pig-farm-controller/internal/logs" + "git.huangwc.com/pig/pig-farm-controller/internal/model" "git.huangwc.com/pig/pig-farm-controller/internal/storage/repository" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" @@ -56,14 +57,14 @@ type LoginResponseData struct { func (c *Controller) Register(ctx *gin.Context) { var req RegisterRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误") return } // 检查用户名是否已存在 _, err := c.userRepo.FindByUsername(req.Username) if err == nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "用户名已存在") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "用户名已存在") return } @@ -71,15 +72,19 @@ func (c *Controller) Register(ctx *gin.Context) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { c.logger.Error("密码哈希处理失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户注册失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户注册失败") return } // 创建用户 - user, err := c.userRepo.CreateUser(req.Username, string(hashedPassword)) - if err != nil { + user := &model.User{ + Username: req.Username, + PasswordHash: string(hashedPassword), + } + + if err := c.userRepo.Create(user); err != nil { c.logger.Error("创建用户失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户注册失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户注册失败") return } @@ -95,28 +100,28 @@ func (c *Controller) Register(ctx *gin.Context) { func (c *Controller) Login(ctx *gin.Context) { var req LoginRequest if err := ctx.ShouldBindJSON(&req); err != nil { - controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误") + controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误") return } // 查找用户 user, err := c.userRepo.FindByUsername(req.Username) if err != nil { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码错误") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "用户名或密码错误") return } // 验证密码 if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { - controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码错误") + controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "用户名或密码错误") return } // 生成JWT token - token, err := middleware.NewAuthMiddleware(c.userRepo).GenerateToken(user.ID, user.Username) + token, err := middleware.GenerateToken(user) if err != nil { c.logger.Error("生成JWT token失败: " + err.Error()) - controller.SendErrorResponse(ctx, http.StatusInternalServerError, "登录失败") + controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "登录失败") return }