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"` } func Success(c *gin.Context, data interface{}) { c.JSON(http.StatusOK, Response{Code: 0, Message: "success", Data: data}) } func Error(c *gin.Context, code int, message string) { c.JSON(http.StatusOK, Response{Code: code, Message: message}) } func BadRequest(c *gin.Context, message string) { Error(c, 400, message) } func Unauthorized(c *gin.Context, message string) { if message == "" { message = "未登录或登录已过期" } c.JSON(http.StatusUnauthorized, Response{Code: 401, Message: message}) } func Forbidden(c *gin.Context, message string) { if message == "" { message = "没有操作权限" } c.JSON(http.StatusForbidden, Response{Code: 403, Message: message}) } func NotFound(c *gin.Context, message string) { if message == "" { message = "资源不存在" } Error(c, 404, 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 { BadRequest(c, "请求参数无效: "+err.Error()) return false } return true }