104 lines
2.3 KiB
Go
104 lines
2.3 KiB
Go
package response
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Response 统一响应结构
|
|
type Response struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
// PageResponse 分页响应结构
|
|
type PageResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
Total int64 `json:"total"`
|
|
Page int `json:"page"`
|
|
PerPage int `json:"per_page"`
|
|
}
|
|
|
|
// Success 成功响应
|
|
func Success(c *gin.Context, data interface{}) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: 200,
|
|
Message: "操作成功",
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
|
|
c.JSON(http.StatusOK, Response{
|
|
Code: 200,
|
|
Message: message,
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// Error 错误响应
|
|
func Error(c *gin.Context, httpCode int, message string) {
|
|
c.JSON(httpCode, Response{
|
|
Code: httpCode,
|
|
Message: message,
|
|
})
|
|
}
|
|
|
|
// ErrorWithData 带数据的错误响应
|
|
func ErrorWithData(c *gin.Context, httpCode int, message string, data interface{}) {
|
|
c.JSON(httpCode, Response{
|
|
Code: httpCode,
|
|
Message: message,
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
// ErrorWithCode 带自定义错误码的错误响应
|
|
func ErrorWithCode(c *gin.Context, httpCode int, code int, message string) {
|
|
c.JSON(httpCode, Response{
|
|
Code: code,
|
|
Message: message,
|
|
})
|
|
}
|
|
|
|
// PageSuccess 分页成功响应
|
|
func PageSuccess(c *gin.Context, data interface{}, total int64, page, perPage int) {
|
|
c.JSON(http.StatusOK, PageResponse{
|
|
Code: 0,
|
|
Message: "操作成功",
|
|
Data: data,
|
|
Total: total,
|
|
Page: page,
|
|
PerPage: perPage,
|
|
})
|
|
}
|
|
|
|
// ParamError 参数错误响应
|
|
func ParamError(c *gin.Context, message string) {
|
|
Error(c, http.StatusBadRequest, message)
|
|
}
|
|
|
|
// Unauthorized 未授权响应
|
|
func Unauthorized(c *gin.Context, message string) {
|
|
Error(c, http.StatusUnauthorized, message)
|
|
}
|
|
|
|
// Forbidden 禁止访问响应
|
|
func Forbidden(c *gin.Context, message string) {
|
|
Error(c, http.StatusForbidden, message)
|
|
}
|
|
|
|
// NotFound 资源未找到响应
|
|
func NotFound(c *gin.Context, message string) {
|
|
Error(c, http.StatusNotFound, message)
|
|
}
|
|
|
|
// InternalError 内部错误响应
|
|
func InternalError(c *gin.Context, message string) {
|
|
Error(c, http.StatusInternalServerError, message)
|
|
}
|