Files
backend/internal/model/response.go

97 lines
2.8 KiB
Go
Raw Normal View History

package model
import "os"
// 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 创建错误响应
// 注意err参数仅在开发环境下显示生产环境不应暴露详细错误信息
func NewErrorResponse(code int, message string, err error) *ErrorResponse {
resp := &ErrorResponse{
Code: code,
Message: message,
}
// 仅在非生产环境下返回详细错误信息
// 可以通过环境变量 ENVIRONMENT 控制
if err != nil && !isProductionEnvironment() {
resp.Error = err.Error()
}
return resp
}
// isProductionEnvironment 检查是否为生产环境
func isProductionEnvironment() bool {
env := os.Getenv("ENVIRONMENT")
return env == "production" || env == "prod"
}
// 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,
}
}