主要功能: - 实现完整的 RBAC 权限系统(账号、角色、权限的多对多关联) - 基于 owner_id + shop_id 的自动数据权限过滤 - 使用 PostgreSQL WITH RECURSIVE 查询下级账号 - Redis 缓存优化下级账号查询性能(30分钟过期) - 支持多租户数据隔离和层级权限管理 技术实现: - 新增 Account、Role、Permission 模型及关联关系表 - 实现 GORM Scopes 自动应用数据权限过滤 - 添加数据库迁移脚本(000002_rbac_data_permission、000003_add_owner_id_shop_id) - 完善错误码定义(1010-1027 为 RBAC 相关错误) - 重构 main.go 采用函数拆分提高可读性 测试覆盖: - 添加 Account、Role、Permission 的集成测试 - 添加数据权限过滤的单元测试和集成测试 - 添加下级账号查询和缓存的单元测试 - 添加 API 回归测试确保向后兼容 文档更新: - 更新 README.md 添加 RBAC 功能说明 - 更新 CLAUDE.md 添加技术栈和开发原则 - 添加 docs/004-rbac-data-permission/ 功能总结和使用指南 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
70 lines
1.8 KiB
Go
70 lines
1.8 KiB
Go
package response
|
||
|
||
import (
|
||
"time"
|
||
|
||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||
"github.com/gofiber/fiber/v2"
|
||
)
|
||
|
||
// Response 统一 API 响应结构
|
||
type Response struct {
|
||
Code int `json:"code"` // 应用错误码(0 = 成功)
|
||
Data any `json:"data"` // 响应数据(对象、数组或 null)
|
||
Message string `json:"msg"` // 可读消息
|
||
Timestamp string `json:"timestamp"` // ISO 8601 时间戳
|
||
}
|
||
|
||
// Success 返回成功响应
|
||
func Success(c *fiber.Ctx, data any) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: data,
|
||
Message: "success",
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|
||
|
||
// Error 返回错误响应
|
||
func Error(c *fiber.Ctx, httpStatus int, code int, message string) error {
|
||
return c.Status(httpStatus).JSON(Response{
|
||
Code: code,
|
||
Data: nil,
|
||
Message: message,
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|
||
|
||
// SuccessWithMessage 返回带自定义消息的成功响应
|
||
func SuccessWithMessage(c *fiber.Ctx, data any, message string) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: data,
|
||
Message: message,
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|
||
|
||
// PaginationData 分页数据结构
|
||
type PaginationData struct {
|
||
Items any `json:"items"` // 数据列表
|
||
Total int64 `json:"total"` // 总数
|
||
Page int `json:"page"` // 当前页码
|
||
Size int `json:"size"` // 每页大小
|
||
}
|
||
|
||
// SuccessWithPagination 返回分页响应
|
||
func SuccessWithPagination(c *fiber.Ctx, items any, total int64, page, size int) error {
|
||
return c.JSON(Response{
|
||
Code: errors.CodeSuccess,
|
||
Data: PaginationData{
|
||
Items: items,
|
||
Total: total,
|
||
Page: page,
|
||
Size: size,
|
||
},
|
||
Message: "success",
|
||
Timestamp: time.Now().Format(time.RFC3339),
|
||
})
|
||
}
|