package response import ( "github.com/gin-gonic/gin" "net/http" "wireguard-ui/component" "wireguard-ui/utils" ) 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 response struct { c *gin.Context } func R(c *gin.Context) response { return response{c} } func (r response) OK() { r.c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "message": "success", }) return } func (r response) OkWithData(data any) { r.c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "message": "success", "data": data, }) } // Paginate // @description: 页码数 // @receiver r // @param data // @param total // @param current // @param size func (r response) Paginate(data any, total int64, current, size int64) { // 处理一下页码、页数量 if current == -1 { current = 1 size = total } // 计算总页码 totalPage := utils.Paginate().Generate(total, int(size)) // 返回结果 r.c.JSON(http.StatusOK, map[string]any{ "code": http.StatusOK, "data": &PageData[any]{Current: int(current), Size: int(size), Total: total, TotalPage: totalPage, Records: data}, "message": "success", }) } func (r response) AuthorizationFailed(msg string) { if msg == "" { msg = "authorized failed" } r.c.JSON(http.StatusUnauthorized, gin.H{ "code": http.StatusUnauthorized, "message": msg, }) } func (r response) Failed() { r.c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, "message": "failed", }) } func (r response) FailedWithError(err any) { var errStr string switch err.(type) { case error: errStr = err.(error).Error() case string: errStr = err.(string) } r.c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, "message": errStr, }) } func (r response) Validator(err error) { r.c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, "message": component.Error(err), }) } func (r response) Internal() { r.c.JSON(http.StatusInternalServerError, gin.H{ "code": http.StatusInternalServerError, "message": "server error", }) }