'init'
This commit is contained in:
61
sc-lktx-backend/internal/common/response/response.go
Normal file
61
sc-lktx-backend/internal/common/response/response.go
Normal file
@@ -0,0 +1,61 @@
|
||||
// 统一 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)
|
||||
}
|
||||
Reference in New Issue
Block a user