75 lines
1.5 KiB
Go
75 lines
1.5 KiB
Go
package core
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
)
|
|
|
|
// 返回数据包装
|
|
type response struct {
|
|
Code int `json:"code"`
|
|
Data interface{} `json:"data"`
|
|
Msg string `json:"msg"`
|
|
}
|
|
|
|
type rs struct {
|
|
ctx *gin.Context
|
|
}
|
|
|
|
// 定义状态码
|
|
const (
|
|
ERROR = http.StatusInternalServerError
|
|
SUCCESS = http.StatusOK
|
|
)
|
|
|
|
func R(ctx *gin.Context) *rs {
|
|
return &rs{ctx: 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)
|
|
}
|
|
|
|
// 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)
|
|
}
|