61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
// Package controller 提供控制器层的公共功能
|
|
// 包含公共响应结构体和处理函数等
|
|
package controller
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// APIResponse 通用API响应结构体
|
|
type APIResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
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 发送成功响应的公共函数
|
|
func SendSuccessResponse(ctx *gin.Context, message string, data interface{}) {
|
|
response := APIResponse{
|
|
Code: SuccessCode,
|
|
Message: message,
|
|
Data: data,
|
|
}
|
|
ctx.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// SendErrorResponse 发送错误响应的公共函数
|
|
func SendErrorResponse(ctx *gin.Context, code int, message string) {
|
|
response := APIResponse{
|
|
Code: code,
|
|
Message: message,
|
|
}
|
|
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)
|
|
}
|