83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
)
|
|
|
|
type PageData[T any] struct {
|
|
Current int `json:"current"` // 当前页码
|
|
Size int `json:"size"` // 每页数量
|
|
Total int64 `json:"total"` // 总数
|
|
TotalPage int `json:"totalPage"` // 总页数
|
|
Records T `json:"records"` // 返回数据
|
|
}
|
|
|
|
type ginResponse struct {
|
|
c *gin.Context
|
|
}
|
|
|
|
func GinResponse(c *gin.Context) ginResponse {
|
|
return ginResponse{c: c}
|
|
}
|
|
|
|
func (r ginResponse) OK() {
|
|
r.c.JSON(http.StatusOK, gin.H{
|
|
"code": http.StatusOK,
|
|
"message": "success",
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) Failed() {
|
|
r.c.JSON(http.StatusBadRequest, gin.H{
|
|
"code": http.StatusBadRequest,
|
|
"message": "bad request",
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) FailedWithErr(msg string, err error) {
|
|
r.c.JSON(http.StatusBadRequest, gin.H{
|
|
"code": http.StatusBadRequest,
|
|
"message": fmt.Errorf("%s: %s", msg, err.Error()).Error(),
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) FailedWithMsg(msg string) {
|
|
r.c.JSON(http.StatusBadRequest, gin.H{
|
|
"code": http.StatusBadRequest,
|
|
"message": msg,
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) AuthorizationFailed() {
|
|
r.c.JSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"message": "请先登陆",
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) OKWithData(data any) {
|
|
r.c.JSON(http.StatusOK, gin.H{
|
|
"code": http.StatusOK,
|
|
"message": "success",
|
|
"data": data,
|
|
})
|
|
}
|
|
|
|
func (r ginResponse) OkWithPage(data any, total int64, current, size int) {
|
|
// 处理一下页码、页数量
|
|
if current == -1 {
|
|
current = 1
|
|
size = int(total)
|
|
}
|
|
// 计算总页码
|
|
totalPage := GenTotalPage(total, size)
|
|
// 返回结果
|
|
r.c.JSON(http.StatusOK, map[string]any{
|
|
"code": http.StatusOK,
|
|
"data": &PageData[any]{Current: current, Size: size, Total: total, TotalPage: totalPage, Records: data},
|
|
"message": "success",
|
|
})
|
|
}
|