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:
@@ -4,14 +4,24 @@ import (
|
||||
"carrotskin/internal/model"
|
||||
"carrotskin/internal/types"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// parseIntWithDefault 将字符串解析为整数,解析失败返回默认值
|
||||
func parseIntWithDefault(s string, defaultVal int) int {
|
||||
val, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return defaultVal
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// GetUserIDFromContext 从上下文获取用户ID,如果不存在返回未授权响应
|
||||
// 返回值: userID, ok (如果ok为false,已经发送了错误响应)
|
||||
func GetUserIDFromContext(c *gin.Context) (int64, bool) {
|
||||
userID, exists := c.Get("user_id")
|
||||
userIDValue, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
|
||||
model.CodeUnauthorized,
|
||||
@@ -20,7 +30,19 @@ func GetUserIDFromContext(c *gin.Context) (int64, bool) {
|
||||
))
|
||||
return 0, false
|
||||
}
|
||||
return userID.(int64), true
|
||||
|
||||
// 安全的类型断言
|
||||
userID, ok := userIDValue.(int64)
|
||||
if !ok {
|
||||
c.JSON(http.StatusInternalServerError, model.NewErrorResponse(
|
||||
model.CodeServerError,
|
||||
"用户ID类型错误",
|
||||
nil,
|
||||
))
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return userID, true
|
||||
}
|
||||
|
||||
// UserToUserInfo 将 User 模型转换为 UserInfo 响应
|
||||
@@ -157,4 +179,3 @@ func RespondWithError(c *gin.Context, err error) {
|
||||
RespondServerError(c, msg, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user