2023-06-15 21:22:51 +08:00
|
|
|
//
|
2023-10-17 17:45:55 +08:00
|
|
|
// resp.go
|
|
|
|
// Copyright (C) 2023 tiglog <me@tiglog.com>
|
2023-06-15 21:22:51 +08:00
|
|
|
//
|
|
|
|
// Distributed under terms of the MIT license.
|
|
|
|
//
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
package gweb
|
2023-06-15 21:22:51 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderJson(c *Context, code int, msg string, data interface{}) {
|
2023-06-15 21:22:51 +08:00
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
"code": code,
|
|
|
|
"msg": msg,
|
|
|
|
"data": data,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// 成功时,返回的 code 为 0
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderOk(c *Context, data interface{}) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, 0, "success", data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 失败时,返回的 code 为指定的 code
|
|
|
|
// 一般会比 http status code 要详细一点
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderFail(c *Context, code int, msg string) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, code, msg, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 成功时,返回自定义消息和数据
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderSuccess(c *Context, msg string, data interface{}) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, 0, msg, data)
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderClientError(c *Context, err error) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, http.StatusBadRequest, err.Error(), nil)
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderServerError(c *Context, err error) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, http.StatusInternalServerError, err.Error(), nil)
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderClientFail(c *Context, msg string) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, http.StatusBadRequest, msg, nil)
|
|
|
|
}
|
|
|
|
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderServerFail(c *Context, msg string) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, http.StatusInternalServerError, msg, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 未发现的各种情况
|
2023-10-17 17:45:55 +08:00
|
|
|
func RenderNotFound(c *Context, msg string) {
|
2023-06-15 21:22:51 +08:00
|
|
|
RenderJson(c, http.StatusNotFound, msg, nil)
|
|
|
|
}
|