Files
huangjin fe3ad20fe2 'init'
2026-06-29 17:34:59 +08:00

62 lines
1.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 统一 API 响应格式,所有接口使用此包返回数据
package response
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Response 统一响应结构code=200 成功,其他为业务错误码
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data,omitempty"`
}
// PageData 分页数据结构
type PageData struct {
List interface{} `json:"list"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
// ===== 成功响应 =====
func Success(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, Response{Code: 200, Message: "success", Data: data})
}
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
c.JSON(http.StatusOK, Response{Code: 200, Message: message, Data: data})
}
func SuccessPage(c *gin.Context, list interface{}, total int64, page, pageSize int) {
c.JSON(http.StatusOK, Response{Code: 200, Message: "success", Data: PageData{
List: list, Total: total, Page: page, PageSize: pageSize,
}})
}
// ===== 错误响应 =====
func Error(c *gin.Context, code int, message string) {
c.JSON(http.StatusOK, Response{Code: code, Message: message})
}
func ErrorWithStatus(c *gin.Context, httpStatus int, code int, message string) {
c.JSON(httpStatus, Response{Code: code, Message: message})
}
func BadRequest(c *gin.Context, message string) { Error(c, 400, message) }
func Unauthorized(c *gin.Context, message string) {
ErrorWithStatus(c, http.StatusUnauthorized, 401, message)
}
func Forbidden(c *gin.Context, message string) {
ErrorWithStatus(c, http.StatusForbidden, 403, message)
}
func NotFound(c *gin.Context, message string) { ErrorWithStatus(c, http.StatusNotFound, 404, message) }
func InternalError(c *gin.Context, message string) {
ErrorWithStatus(c, http.StatusInternalServerError, 500, message)
}