golib/helper/resp_helper.go
2023-06-15 21:22:51 +08:00

60 lines
1.3 KiB
Go

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