86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
package core
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
"online_code/utils"
|
|
)
|
|
|
|
// 返回数据包装
|
|
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 interface{}, msg string) {
|
|
//if data == nil {
|
|
// data = map[string]interface{}{}
|
|
//}
|
|
|
|
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 interface{}) {
|
|
r.Result(SUCCESS, data, "操作成功")
|
|
}
|
|
|
|
// OkDetailed 自定义消息和内容的成功返回
|
|
func (r rs) OkDetailed(data interface{}, message string) {
|
|
r.Result(SUCCESS, data, message)
|
|
}
|
|
|
|
// OkDataPage 返回分页数据
|
|
func (r rs) OkDataPage(count int64, page PageData) {
|
|
// 计算总页码
|
|
totalPage := utils.GenTotalPage(count, page.Size)
|
|
page.TotalPage = totalPage
|
|
// 返回结果
|
|
r.Result(SUCCESS, page, "操作成功")
|
|
}
|
|
|
|
// 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)
|
|
}
|