feat: 引入依赖注入模式

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

同时包含之前的安全修复:
- CORS配置安全加固
- 头像URL验证安全修复
- JWT algorithm confusion漏洞修复
- Recovery中间件增强
- 敏感错误信息泄露修复
- 类型断言安全修复
This commit is contained in:
lan
2025-12-02 17:40:39 +08:00
parent 373c61f625
commit f7589ebbb8
25 changed files with 2029 additions and 139 deletions

View File

@@ -1,10 +1,12 @@
package model
import "os"
// Response 通用API响应结构
type Response struct {
Code int `json:"code"` // 业务状态码
Message string `json:"message"` // 响应消息
Data interface{} `json:"data,omitempty"` // 响应数据
Code int `json:"code"` // 业务状态码
Message string `json:"message"` // 响应消息
Data interface{} `json:"data,omitempty"` // 响应数据
}
// PaginationResponse 分页响应结构
@@ -12,9 +14,9 @@ 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"` // 每页数量
Total int64 `json:"total"` // 总记录数
Page int `json:"page"` // 当前页码
PerPage int `json:"per_page"` // 每页数量
}
// ErrorResponse 错误响应
@@ -26,14 +28,14 @@ type ErrorResponse struct {
// 常用状态码
const (
CodeSuccess = 200 // 成功
CodeCreated = 201 // 创建成功
CodeBadRequest = 400 // 请求参数错误
CodeUnauthorized = 401 // 未授权
CodeForbidden = 403 // 禁止访问
CodeNotFound = 404 // 资源不存在
CodeConflict = 409 // 资源冲突
CodeServerError = 500 // 服务器错误
CodeSuccess = 200 // 成功
CodeCreated = 201 // 创建成功
CodeBadRequest = 400 // 请求参数错误
CodeUnauthorized = 401 // 未授权
CodeForbidden = 403 // 禁止访问
CodeNotFound = 404 // 资源不存在
CodeConflict = 409 // 资源冲突
CodeServerError = 500 // 服务器错误
)
// 常用响应消息
@@ -61,17 +63,26 @@ func NewSuccessResponse(data interface{}) *Response {
}
// NewErrorResponse 创建错误响应
// 注意err参数仅在开发环境下显示生产环境不应暴露详细错误信息
func NewErrorResponse(code int, message string, err error) *ErrorResponse {
resp := &ErrorResponse{
Code: code,
Message: message,
}
if err != nil {
// 仅在非生产环境下返回详细错误信息
// 可以通过环境变量 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{