86 lines
2.4 KiB
Go
86 lines
2.4 KiB
Go
package model
|
|
|
|
// Response 通用API响应结构
|
|
type Response struct {
|
|
Code int `json:"code"` // 业务状态码
|
|
Message string `json:"message"` // 响应消息
|
|
Data interface{} `json:"data,omitempty"` // 响应数据
|
|
}
|
|
|
|
// PaginationResponse 分页响应结构
|
|
type PaginationResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data"`
|
|
Total int64 `json:"total"` // 总记录数
|
|
Page int `json:"page"` // 当前页码
|
|
PerPage int `json:"per_page"` // 每页数量
|
|
}
|
|
|
|
// ErrorResponse 错误响应
|
|
type ErrorResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Error string `json:"error,omitempty"` // 详细错误信息(仅开发环境)
|
|
}
|
|
|
|
// 常用状态码
|
|
const (
|
|
CodeSuccess = 200 // 成功
|
|
CodeCreated = 201 // 创建成功
|
|
CodeBadRequest = 400 // 请求参数错误
|
|
CodeUnauthorized = 401 // 未授权
|
|
CodeForbidden = 403 // 禁止访问
|
|
CodeNotFound = 404 // 资源不存在
|
|
CodeConflict = 409 // 资源冲突
|
|
CodeServerError = 500 // 服务器错误
|
|
)
|
|
|
|
// 常用响应消息
|
|
const (
|
|
MsgSuccess = "操作成功"
|
|
MsgCreated = "创建成功"
|
|
MsgBadRequest = "请求参数错误"
|
|
MsgUnauthorized = "未授权,请先登录"
|
|
MsgForbidden = "权限不足"
|
|
MsgNotFound = "资源不存在"
|
|
MsgConflict = "资源已存在"
|
|
MsgServerError = "服务器内部错误"
|
|
MsgInvalidToken = "无效的令牌"
|
|
MsgTokenExpired = "令牌已过期"
|
|
MsgInvalidCredentials = "用户名或密码错误"
|
|
)
|
|
|
|
// NewSuccessResponse 创建成功响应
|
|
func NewSuccessResponse(data interface{}) *Response {
|
|
return &Response{
|
|
Code: CodeSuccess,
|
|
Message: MsgSuccess,
|
|
Data: data,
|
|
}
|
|
}
|
|
|
|
// NewErrorResponse 创建错误响应
|
|
func NewErrorResponse(code int, message string, err error) *ErrorResponse {
|
|
resp := &ErrorResponse{
|
|
Code: code,
|
|
Message: message,
|
|
}
|
|
if err != nil {
|
|
resp.Error = err.Error()
|
|
}
|
|
return resp
|
|
}
|
|
|
|
// NewPaginationResponse 创建分页响应
|
|
func NewPaginationResponse(data interface{}, total int64, page, perPage int) *PaginationResponse {
|
|
return &PaginationResponse{
|
|
Code: CodeSuccess,
|
|
Message: MsgSuccess,
|
|
Data: data,
|
|
Total: total,
|
|
Page: page,
|
|
PerPage: perPage,
|
|
}
|
|
}
|