优化接口返回值状态码

This commit is contained in:
2025-09-08 12:30:33 +08:00
parent c7e2aaee89
commit 6f3f7db870
4 changed files with 55 additions and 34 deletions

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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)
}

View File

@@ -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
}