package utils import ( "net/http" "strconv" "github.com/gin-gonic/gin" ) type Response struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data,omitempty"` } type PageData struct { List interface{} `json:"list"` Total int64 `json:"total"` Page int `json:"page"` PageSize int `json:"pageSize"` } // Success 返回200状态码的成功响应 func Success(c *gin.Context, data interface{}) { c.JSON(http.StatusOK, Response{Code: 0, Message: "success", Data: data}) } // Error 返回指定HTTP状态码的错误响应,status code与业务code一致 func Error(c *gin.Context, code int, message string) { httpStatus := code if httpStatus < 100 || httpStatus >= 600 { httpStatus = http.StatusBadRequest } c.JSON(httpStatus, Response{Code: code, Message: message}) } // BadRequest 返回400状态码 func BadRequest(c *gin.Context, message string) { c.JSON(http.StatusBadRequest, Response{Code: 400, Message: message}) } // Unauthorized 返回401状态码 func Unauthorized(c *gin.Context, message string) { if message == "" { message = "未登录或登录已过期" } c.JSON(http.StatusUnauthorized, Response{Code: 401, Message: message}) } // Forbidden 返回403状态码 func Forbidden(c *gin.Context, message string) { if message == "" { message = "没有操作权限" } c.JSON(http.StatusForbidden, Response{Code: 403, Message: message}) } // NotFound 返回404状态码 func NotFound(c *gin.Context, message string) { if message == "" { message = "资源不存在" } c.JSON(http.StatusNotFound, Response{Code: 404, Message: message}) } // InternalServerError 返回500状态码 func InternalServerError(c *gin.Context, message string) { if message == "" { message = "服务器内部错误" } c.JSON(http.StatusInternalServerError, Response{Code: 500, Message: message}) } // ValidationError 返回422状态码(参数校验失败) func ValidationError(c *gin.Context, message string) { if message == "" { message = "参数校验失败" } c.JSON(http.StatusUnprocessableEntity, Response{Code: 422, Message: message}) } func Pagination(c *gin.Context) (page, pageSize int) { page, pageSize = 1, 10 if p := c.Query("page"); p != "" { if v, err := strconv.Atoi(p); err == nil && v > 0 { page = v } } if ps := c.Query("pageSize"); ps != "" { if v, err := strconv.Atoi(ps); err == nil && v > 0 && v <= 100 { pageSize = v } } return } func IntParam(c *gin.Context, key string) (int, error) { return strconv.Atoi(c.Param(key)) } func BindAndValidate(c *gin.Context, obj interface{}) bool { if err := c.ShouldBindJSON(obj); err != nil { ValidationError(c, "请求参数无效: "+err.Error()) return false } return true }