88 lines
2.1 KiB
Go
88 lines
2.1 KiB
Go
|
|
// Package utils 提供通用工具函数
|
|||
|
|
// 包括统一的 JSON 响应格式化、错误处理等
|
|||
|
|
package utils
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"net/http"
|
|||
|
|
|
|||
|
|
"github.com/gin-gonic/gin"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// Response 统一API响应结构体
|
|||
|
|
type Response struct {
|
|||
|
|
Code int `json:"code"` // 业务状态码:0=成功,非0=失败
|
|||
|
|
Message string `json:"message"` // 提示信息
|
|||
|
|
Data interface{} `json:"data"` // 响应数据,可以是任意类型
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Success 返回成功响应
|
|||
|
|
// c: Gin上下文
|
|||
|
|
// data: 响应数据
|
|||
|
|
func Success(c *gin.Context, data interface{}) {
|
|||
|
|
c.JSON(http.StatusOK, Response{
|
|||
|
|
Code: 0,
|
|||
|
|
Message: "success",
|
|||
|
|
Data: data,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// SuccessWithMessage 返回带自定义消息的成功响应
|
|||
|
|
// c: Gin上下文
|
|||
|
|
// message: 自定义提示信息
|
|||
|
|
// data: 响应数据
|
|||
|
|
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
|
|||
|
|
c.JSON(http.StatusOK, Response{
|
|||
|
|
Code: 0,
|
|||
|
|
Message: message,
|
|||
|
|
Data: data,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Error 返回错误响应
|
|||
|
|
// c: Gin上下文
|
|||
|
|
// code: 业务错误码(非0)
|
|||
|
|
// message: 错误提示信息
|
|||
|
|
func Error(c *gin.Context, code int, message string) {
|
|||
|
|
c.JSON(http.StatusOK, Response{
|
|||
|
|
Code: code,
|
|||
|
|
Message: message,
|
|||
|
|
Data: nil,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ErrorWithHTTP 返回带HTTP状态码的错误响应
|
|||
|
|
// c: Gin上下文
|
|||
|
|
// httpCode: HTTP状态码
|
|||
|
|
// code: 业务错误码
|
|||
|
|
// message: 错误提示信息
|
|||
|
|
func ErrorWithHTTP(c *gin.Context, httpCode int, code int, message string) {
|
|||
|
|
c.JSON(httpCode, Response{
|
|||
|
|
Code: code,
|
|||
|
|
Message: message,
|
|||
|
|
Data: nil,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// PageResult 分页查询结果结构体
|
|||
|
|
type PageResult struct {
|
|||
|
|
List interface{} `json:"list"` // 数据列表
|
|||
|
|
Total int64 `json:"total"` // 总记录数
|
|||
|
|
Page int `json:"page"` // 当前页码
|
|||
|
|
PageSize int `json:"pageSize"` // 每页条数
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// SuccessPage 返回分页查询成功响应
|
|||
|
|
// c: Gin上下文
|
|||
|
|
// list: 数据列表
|
|||
|
|
// total: 总记录数
|
|||
|
|
// page: 当前页码
|
|||
|
|
// pageSize: 每页条数
|
|||
|
|
func SuccessPage(c *gin.Context, list interface{}, total int64, page, pageSize int) {
|
|||
|
|
Success(c, PageResult{
|
|||
|
|
List: list,
|
|||
|
|
Total: total,
|
|||
|
|
Page: page,
|
|||
|
|
PageSize: pageSize,
|
|||
|
|
})
|
|||
|
|
}
|