90 lines
2.1 KiB
Go
90 lines
2.1 KiB
Go
|
|
// Package utils 提供通用工具函数
|
||
|
|
package utils
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Response 统一API响应结构
|
||
|
|
type Response struct {
|
||
|
|
Code int `json:"code"` // 业务状态码, 0=成功
|
||
|
|
Message string `json:"message"` // 提示信息
|
||
|
|
Data interface{} `json:"data"` // 响应数据
|
||
|
|
}
|
||
|
|
|
||
|
|
// PageResponse 分页响应结构
|
||
|
|
type PageResponse struct {
|
||
|
|
Code int `json:"code"`
|
||
|
|
Message string `json:"message"`
|
||
|
|
Data interface{} `json:"data"`
|
||
|
|
Total int64 `json:"total"` // 总记录数
|
||
|
|
Page int `json:"page"` // 当前页码
|
||
|
|
Size int `json:"size"` // 每页大小
|
||
|
|
}
|
||
|
|
|
||
|
|
// Success 返回成功响应
|
||
|
|
func Success(c *gin.Context, data interface{}) {
|
||
|
|
c.JSON(http.StatusOK, Response{
|
||
|
|
Code: 0,
|
||
|
|
Message: "success",
|
||
|
|
Data: data,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
// SuccessWithMessage 返回带消息的成功响应
|
||
|
|
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
|
||
|
|
c.JSON(http.StatusOK, Response{
|
||
|
|
Code: 0,
|
||
|
|
Message: message,
|
||
|
|
Data: data,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
// Error 返回错误响应
|
||
|
|
func Error(c *gin.Context, httpCode int, bizCode int, message string) {
|
||
|
|
c.JSON(httpCode, Response{
|
||
|
|
Code: bizCode,
|
||
|
|
Message: message,
|
||
|
|
Data: nil,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
// BadRequest 返回400错误
|
||
|
|
func BadRequest(c *gin.Context, message string) {
|
||
|
|
Error(c, http.StatusBadRequest, 400, message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Unauthorized 返回401错误
|
||
|
|
func Unauthorized(c *gin.Context, message string) {
|
||
|
|
Error(c, http.StatusUnauthorized, 401, message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Forbidden 返回403错误
|
||
|
|
func Forbidden(c *gin.Context, message string) {
|
||
|
|
Error(c, http.StatusForbidden, 403, message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// NotFound 返回404错误
|
||
|
|
func NotFound(c *gin.Context, message string) {
|
||
|
|
Error(c, http.StatusNotFound, 404, message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// ServerError 返回500错误
|
||
|
|
func ServerError(c *gin.Context, message string) {
|
||
|
|
Error(c, http.StatusInternalServerError, 500, message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// PageSuccess 返回分页成功响应
|
||
|
|
func PageSuccess(c *gin.Context, data interface{}, total int64, page, size int) {
|
||
|
|
c.JSON(http.StatusOK, PageResponse{
|
||
|
|
Code: 0,
|
||
|
|
Message: "success",
|
||
|
|
Data: data,
|
||
|
|
Total: total,
|
||
|
|
Page: page,
|
||
|
|
Size: size,
|
||
|
|
})
|
||
|
|
}
|