优化接口返回值状态码
This commit is contained in:
@@ -3,8 +3,6 @@
|
|||||||
package device
|
package device
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.huangwc.com/pig/pig-farm-controller/internal/api/middleware"
|
"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/controller"
|
||||||
"git.huangwc.com/pig/pig-farm-controller/internal/logs"
|
"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")
|
userValue, exists := ctx.Get("user")
|
||||||
if !exists {
|
if !exists {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, ok := userValue.(*middleware.AuthUser)
|
user, ok := userValue.(*middleware.AuthUser)
|
||||||
if !ok {
|
if !ok {
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var req SwitchRequest
|
var req SwitchRequest
|
||||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +76,7 @@ func (c *Controller) Switch(ctx *gin.Context) {
|
|||||||
"设备控制成功",
|
"设备控制成功",
|
||||||
); err != nil {
|
); err != nil {
|
||||||
c.logger.Error("创建设备控制记录失败: " + err.Error())
|
c.logger.Error("创建设备控制记录失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "设备控制失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "设备控制失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
package operation
|
package operation
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"git.huangwc.com/pig/pig-farm-controller/internal/api/middleware"
|
"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")
|
userValue, exists := ctx.Get("user")
|
||||||
if !exists {
|
if !exists {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, ok := userValue.(*middleware.AuthUser)
|
user, ok := userValue.(*middleware.AuthUser)
|
||||||
if !ok {
|
if !ok {
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var req CreateRequest
|
var req CreateRequest
|
||||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +69,7 @@ func (c *Controller) Create(ctx *gin.Context) {
|
|||||||
|
|
||||||
if err := c.operationHistoryRepo.Create(operation); err != nil {
|
if err := c.operationHistoryRepo.Create(operation); err != nil {
|
||||||
c.logger.Error("创建操作历史记录失败: " + err.Error())
|
c.logger.Error("创建操作历史记录失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "创建操作历史记录失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "创建操作历史记录失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,13 +81,13 @@ func (c *Controller) ListByUser(ctx *gin.Context) {
|
|||||||
// 从上下文中获取用户信息
|
// 从上下文中获取用户信息
|
||||||
userValue, exists := ctx.Get("user")
|
userValue, exists := ctx.Get("user")
|
||||||
if !exists {
|
if !exists {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, ok := userValue.(*middleware.AuthUser)
|
user, ok := userValue.(*middleware.AuthUser)
|
||||||
if !ok {
|
if !ok {
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +110,7 @@ func (c *Controller) ListByUser(ctx *gin.Context) {
|
|||||||
operations, err := c.operationHistoryRepo.ListByUserID(user.ID, offset, limit)
|
operations, err := c.operationHistoryRepo.ListByUserID(user.ID, offset, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.logger.Error("获取操作历史记录失败: " + err.Error())
|
c.logger.Error("获取操作历史记录失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "获取操作历史记录失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "获取操作历史记录失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +122,7 @@ func (c *Controller) Get(ctx *gin.Context) {
|
|||||||
// 获取操作历史记录ID
|
// 获取操作历史记录ID
|
||||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "无效的操作历史记录ID")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "无效的操作历史记录ID")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,26 +130,26 @@ func (c *Controller) Get(ctx *gin.Context) {
|
|||||||
operation, err := c.operationHistoryRepo.FindByID(uint(id))
|
operation, err := c.operationHistoryRepo.FindByID(uint(id))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.logger.Error("获取操作历史记录失败: " + err.Error())
|
c.logger.Error("获取操作历史记录失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "获取操作历史记录失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "获取操作历史记录失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从上下文中获取用户信息
|
// 从上下文中获取用户信息
|
||||||
userValue, exists := ctx.Get("user")
|
userValue, exists := ctx.Get("user")
|
||||||
if !exists {
|
if !exists {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "无法获取用户信息")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "无法获取用户信息")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, ok := userValue.(*middleware.AuthUser)
|
user, ok := userValue.(*middleware.AuthUser)
|
||||||
if !ok {
|
if !ok {
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户信息格式错误")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户信息格式错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查操作历史记录是否属于当前用户
|
// 检查操作历史记录是否属于当前用户
|
||||||
if operation.UserID != user.ID {
|
if operation.UserID != user.ID {
|
||||||
controller.SendErrorResponse(ctx, http.StatusForbidden, "无权访问该操作历史记录")
|
controller.SendErrorResponse(ctx, controller.ForbiddenCode, "无权访问该操作历史记录")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,27 +15,46 @@ type APIResponse struct {
|
|||||||
Data interface{} `json:"data,omitempty"`
|
Data interface{} `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 自定义状态码常量
|
||||||
|
const (
|
||||||
|
SuccessCode = 0 // 成功
|
||||||
|
InvalidParameterCode = 1001 // 参数无效
|
||||||
|
UnauthorizedCode = 1002 // 未授权
|
||||||
|
ForbiddenCode = 1003 // 禁止访问
|
||||||
|
NotFoundCode = 1004 // 资源未找到
|
||||||
|
InternalServerErrorCode = 1005 // 内部服务器错误
|
||||||
|
)
|
||||||
|
|
||||||
// SuccessResponseData 成功响应数据结构体
|
// SuccessResponseData 成功响应数据结构体
|
||||||
type SuccessResponseData struct {
|
type SuccessResponseData struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Data interface{} `json:"data,omitempty"`
|
Data interface{} `json:"data,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// sendSuccessResponse 发送成功响应的公共函数
|
// SendSuccessResponse 发送成功响应的公共函数
|
||||||
func SendSuccessResponse(ctx *gin.Context, message string, data interface{}) {
|
func SendSuccessResponse(ctx *gin.Context, message string, data interface{}) {
|
||||||
response := APIResponse{
|
response := APIResponse{
|
||||||
Code: http.StatusOK,
|
Code: SuccessCode,
|
||||||
Message: message,
|
Message: message,
|
||||||
Data: data,
|
Data: data,
|
||||||
}
|
}
|
||||||
ctx.JSON(http.StatusOK, response)
|
ctx.JSON(http.StatusOK, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sendErrorResponse 发送错误响应的公共函数
|
// SendErrorResponse 发送错误响应的公共函数
|
||||||
func SendErrorResponse(ctx *gin.Context, code int, message string) {
|
func SendErrorResponse(ctx *gin.Context, code int, message string) {
|
||||||
response := APIResponse{
|
response := APIResponse{
|
||||||
Code: code,
|
Code: code,
|
||||||
Message: message,
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"git.huangwc.com/pig/pig-farm-controller/internal/api/middleware"
|
"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/controller"
|
||||||
"git.huangwc.com/pig/pig-farm-controller/internal/logs"
|
"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"
|
"git.huangwc.com/pig/pig-farm-controller/internal/storage/repository"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -56,14 +57,14 @@ type LoginResponseData struct {
|
|||||||
func (c *Controller) Register(ctx *gin.Context) {
|
func (c *Controller) Register(ctx *gin.Context) {
|
||||||
var req RegisterRequest
|
var req RegisterRequest
|
||||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查用户名是否已存在
|
// 检查用户名是否已存在
|
||||||
_, err := c.userRepo.FindByUsername(req.Username)
|
_, err := c.userRepo.FindByUsername(req.Username)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "用户名已存在")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "用户名已存在")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,15 +72,19 @@ func (c *Controller) Register(ctx *gin.Context) {
|
|||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.logger.Error("密码哈希处理失败: " + err.Error())
|
c.logger.Error("密码哈希处理失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户注册失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户注册失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建用户
|
// 创建用户
|
||||||
user, err := c.userRepo.CreateUser(req.Username, string(hashedPassword))
|
user := &model.User{
|
||||||
if err != nil {
|
Username: req.Username,
|
||||||
|
PasswordHash: string(hashedPassword),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.userRepo.Create(user); err != nil {
|
||||||
c.logger.Error("创建用户失败: " + err.Error())
|
c.logger.Error("创建用户失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "用户注册失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "用户注册失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,28 +100,28 @@ func (c *Controller) Register(ctx *gin.Context) {
|
|||||||
func (c *Controller) Login(ctx *gin.Context) {
|
func (c *Controller) Login(ctx *gin.Context) {
|
||||||
var req LoginRequest
|
var req LoginRequest
|
||||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, "请求参数错误")
|
controller.SendErrorResponse(ctx, controller.InvalidParameterCode, "请求参数错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 查找用户
|
// 查找用户
|
||||||
user, err := c.userRepo.FindByUsername(req.Username)
|
user, err := c.userRepo.FindByUsername(req.Username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码错误")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "用户名或密码错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证密码
|
// 验证密码
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
||||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码错误")
|
controller.SendErrorResponse(ctx, controller.UnauthorizedCode, "用户名或密码错误")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 生成JWT token
|
// 生成JWT token
|
||||||
token, err := middleware.NewAuthMiddleware(c.userRepo).GenerateToken(user.ID, user.Username)
|
token, err := middleware.GenerateToken(user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.logger.Error("生成JWT token失败: " + err.Error())
|
c.logger.Error("生成JWT token失败: " + err.Error())
|
||||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "登录失败")
|
controller.SendErrorResponse(ctx, controller.InternalServerErrorCode, "登录失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user