86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package core
|
|
|
|
import (
|
|
"Lee-WineList/utils"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 返回数据包装
|
|
type response struct {
|
|
Code int `json:"code"`
|
|
Data any `json:"data"`
|
|
Msg string `json:"message"`
|
|
}
|
|
|
|
type rs struct {
|
|
ctx *gin.Context
|
|
}
|
|
|
|
// 定义状态码
|
|
const (
|
|
ERROR = http.StatusInternalServerError
|
|
SUCCESS = http.StatusOK
|
|
)
|
|
|
|
func R(ctx *gin.Context) *rs {
|
|
return &rs{ctx}
|
|
}
|
|
|
|
// Result 手动组装返回结果
|
|
func (r rs) Result(code int, data any, msg string) {
|
|
//if data == nil {
|
|
// data = map[string]any{}
|
|
//}
|
|
|
|
r.ctx.JSON(code, response{
|
|
code,
|
|
data,
|
|
msg,
|
|
})
|
|
}
|
|
|
|
// Ok 返回无数据的成功
|
|
func (r rs) Ok() {
|
|
r.Result(SUCCESS, nil, "操作成功")
|
|
}
|
|
|
|
// OkWithMessage 返回自定义成功的消息
|
|
func (r rs) OkWithMessage(message string) {
|
|
r.Result(SUCCESS, nil, message)
|
|
}
|
|
|
|
// OkWithData 自定义内容的成功返回
|
|
func (r rs) OkWithData(data any) {
|
|
r.Result(SUCCESS, data, "操作成功")
|
|
}
|
|
|
|
// OkWithPageData 返回分页数据
|
|
func (r rs) OkWithPageData(data any, total int64, current, size int) {
|
|
// 计算总页码
|
|
totalPage := utils.GenTotalPage(total, size)
|
|
// 返回结果
|
|
r.Result(SUCCESS, PageData{Current: current, Size: size, Total: total, TotalPage: totalPage, Records: data}, "操作成功")
|
|
}
|
|
|
|
// OkDetailed 自定义消息和内容的成功返回
|
|
func (r rs) OkDetailed(data any, message string) {
|
|
r.Result(SUCCESS, data, message)
|
|
}
|
|
|
|
// Fail 返回默认失败
|
|
func (r rs) Fail() {
|
|
r.Result(ERROR, nil, "操作失败")
|
|
}
|
|
|
|
// FailWithMessage 返回默认状态码自定义消息的失败
|
|
func (r rs) FailWithMessage(message string) {
|
|
r.Result(ERROR, nil, message)
|
|
}
|
|
|
|
// FailWithMessageAndCode 返回自定义消息和状态码的失败
|
|
func (r rs) FailWithMessageAndCode(message string, code int) {
|
|
r.Result(code, nil, message)
|
|
}
|