优化接口返回值状态码
This commit is contained in:
@@ -15,27 +15,46 @@ type APIResponse struct {
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// 自定义状态码常量
|
||||
const (
|
||||
SuccessCode = 0 // 成功
|
||||
InvalidParameterCode = 1001 // 参数无效
|
||||
UnauthorizedCode = 1002 // 未授权
|
||||
ForbiddenCode = 1003 // 禁止访问
|
||||
NotFoundCode = 1004 // 资源未找到
|
||||
InternalServerErrorCode = 1005 // 内部服务器错误
|
||||
)
|
||||
|
||||
// SuccessResponseData 成功响应数据结构体
|
||||
type SuccessResponseData struct {
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// sendSuccessResponse 发送成功响应的公共函数
|
||||
// SendSuccessResponse 发送成功响应的公共函数
|
||||
func SendSuccessResponse(ctx *gin.Context, message string, data interface{}) {
|
||||
response := APIResponse{
|
||||
Code: http.StatusOK,
|
||||
Code: SuccessCode,
|
||||
Message: message,
|
||||
Data: data,
|
||||
}
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// sendErrorResponse 发送错误响应的公共函数
|
||||
// SendErrorResponse 发送错误响应的公共函数
|
||||
func SendErrorResponse(ctx *gin.Context, code int, message string) {
|
||||
response := APIResponse{
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
ctx.JSON(code, response)
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// SendHTTPErrorResponse 发送HTTP错误响应的公共函数
|
||||
func SendHTTPErrorResponse(ctx *gin.Context, httpCode int, code int, message string) {
|
||||
response := APIResponse{
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
ctx.JSON(httpCode, response)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user