Files
backend/internal/model/response.go
lan f7589ebbb8 feat: 引入依赖注入模式
- 创建Repository接口定义(UserRepository、ProfileRepository、TextureRepository等)
- 创建Repository接口实现
- 创建依赖注入容器(container.Container)
- 改造Handler层使用依赖注入(AuthHandler、UserHandler、TextureHandler)
- 创建新的路由注册方式(RegisterRoutesWithDI)
- 提供main.go示例文件展示如何使用依赖注入

同时包含之前的安全修复:
- CORS配置安全加固
- 头像URL验证安全修复
- JWT algorithm confusion漏洞修复
- Recovery中间件增强
- 敏感错误信息泄露修复
- 类型断言安全修复
2025-12-02 17:40:39 +08:00

97 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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,
}
}