API 约定
地址与响应信封
- 基础地址:
http://localhost:8001/api/v1(app.api_prefix可配)。 - 统一信封(
internal/pkg/response),与 Python 版逐字段一致:
go
type Body struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
}json
// 成功
{ "code": 200, "msg": "success", "data": { ... } }
// 分页 data
{ "total": 123, "page": 1, "page_size": 20, "items": [ ... ] }- i18n 变体:
response.SuccessT / ErrorT按 Locale 中间件解析的Accept-Language翻译 msg(core.T(locale, key, params)),支持{name}占位符插值。 - 字段命名全局 snake_case(struct tag 保证),三版底座一致。
错误码语义
与 Python 版对齐:200 成功(前端判据 code === 200);401 未登录 / token 失效;403 权限不足;404 资源不存在;409 冲突;422 校验失败;429 限流(全局 API 限流 + 登录防爆破 + AI 配额)。
认证
text
Authorization: Bearer <access_token>- 登录:
POST /api/v1/auth/login(middleware.LoginGuard前置 +RateLimit("login", 10/min)防爆破)。 - 刷新:
POST /api/v1/auth/refresh—— 免登录(access 过期后才能换新,放 authed 组会死锁)。 - 登出:
POST /api/v1/auth/logout→ jti/token 进内存 TokenStore 黑名单(后台 30 分钟批量清理;token_version改密失效双保险)。
路由三级分组(router.go 实景)
| 组 | 注册方式 | 典型路由 |
|---|---|---|
| public | api.Group("") | /auth/login、/auth/refresh、/settings/public、/health、/i18n/locales、/i18n/messages/:locale |
| authed | Use(middleware.JWTAuth()) | /auth/userinfo、/auth/profile(GET/PUT)、/auth/profile/password、/auth/logout |
| perm | Use(JWTAuth) + 行内 RequirePermission | /users(system:user:list)、/users/:id 等 |
行内权限写法:
go
users.GET("", middleware.RequirePermission("system:user:list"), userH.List)
users.POST("", middleware.RequirePermission("system:user:add"), userH.Create)
users.POST("/:id/kick", middleware.RequirePermission("system:user:edit"), userH.Kick) // 在线踢下线主要资源
| 分组 | 文件 | 说明 |
|---|---|---|
| 认证 | auth.go | 登录 / 刷新 / 用户信息 / 个人资料 |
| 用户 / 角色 / 菜单 / 部门 | user.go 等 | RBAC(含在线列表 / 踢下线;/roles/all 免权限) |
| 文件 | 文件管理 | 上传下载 |
| 日志 | 操作 / 登录日志 | AuditQueue 异步入库 |
| 设置 | system.go / setting | 键值配置(admin_path 运行时覆盖) |
| 插件 | plugin.go | 列表 / 启停 / ZIP 上传(L2) |
| AI | ai_provider.go ai_chat.go ai_chat_runs.go ai_chat_stream.go ai_tools.go ai_runner.go | 供应商密钥 / 会话 / Run / SSE 流式 / Function Calling |
| MCP | mcp.go | 工具 / 资源 / 提示词 / 审计日志 |
| 仪表盘 | dashboard.go | 业务统计 |
| i18n | i18n.go | 语言注册表 + 翻译条目(DB 覆盖层) |
新增一个业务模块的标准写法(以「公告管理」为例)
- 模型:
internal/model/notice.go嵌入BaseModel(自动获得 id / created_at / updated_at / deleted 软删除),TableName() { return "sys_notice" };加入bootstrap.allModels(开发期 auto_migrate)。 - schema:
internal/schema/notice.go请求 / 响应 DTO(json tag snake_case)。 - DAL:
internal/dal/notice.go数据访问。 - handler:
internal/api/notice.go,返回response.Success(...);行内挂middleware.RequirePermission("system:notice:list")。 - 路由:
router.go的 perm 组注册(perm.Group("/notices"))。 - 菜单 / 权限码:种子
sys_menu(permission 存system:notice:*);前端共用 Vue 源码按菜单 component 建页面。
语义对齐说明
三版契约逐一对齐;遇到行为差异以 Python 版为准,并在 KevinLiss/ApeAdmin-Gin 仓库提 issue。