package utils import ( "net/http" "strconv" "github.com/gin-gonic/gin" ) // 统一响应码 const ( CodeSuccess = 0 CodeError = 1 CodeParamError = 400 CodeUnauthorized = 401 CodeForbidden = 403 CodeNotFound = 404 CodeServerErr = 500 ) // Response 统一响应结构 type Response struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data,omitempty"` } // PageData 分页响应结构 type PageData struct { List interface{} `json:"list"` Total int64 `json:"total"` Page int `json:"page"` PageSize int `json:"page_size"` } // OK 成功响应 func OK(c *gin.Context, data interface{}) { c.JSON(http.StatusOK, Response{Code: CodeSuccess, Message: "success", Data: data}) } // OKMsg 成功响应(仅消息) func OKMsg(c *gin.Context, msg string) { c.JSON(http.StatusOK, Response{Code: CodeSuccess, Message: msg}) } // OKPage 分页成功响应 func OKPage(c *gin.Context, list interface{}, total int64, page, pageSize int) { c.JSON(http.StatusOK, Response{ Code: CodeSuccess, Message: "success", Data: PageData{List: list, Total: total, Page: page, PageSize: pageSize}, }) } // Fail 失败响应 func Fail(c *gin.Context, httpCode, code int, msg string) { c.JSON(httpCode, Response{Code: code, Message: msg}) } // FailMsg 默认400失败响应 func FailMsg(c *gin.Context, msg string) { Fail(c, http.StatusBadRequest, CodeError, msg) } // Unauthorized 401 func Unauthorized(c *gin.Context, msg string) { c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Code: CodeUnauthorized, Message: msg}) } // Forbidden 403 func Forbidden(c *gin.Context, msg string) { c.AbortWithStatusJSON(http.StatusForbidden, Response{Code: CodeForbidden, Message: msg}) } // NotFound 404 func NotFound(c *gin.Context, msg string) { c.JSON(http.StatusNotFound, Response{Code: CodeNotFound, Message: msg}) } // ServerError 500 func ServerError(c *gin.Context, msg string) { c.JSON(http.StatusInternalServerError, Response{Code: CodeServerErr, Message: msg}) } // ParsePage 解析分页参数 func ParsePage(c *gin.Context) (page, pageSize int) { page = 1 pageSize = 20 if v, err := strconv.Atoi(c.Query("page")); err == nil && v > 0 { page = v } if v, err := strconv.Atoi(c.Query("page_size")); err == nil && v > 0 && v <= 100 { pageSize = v } return }