Files
taotie-api/CODEBUDDY.md

65 lines
3.1 KiB
Markdown
Raw Permalink 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.
# CODEBUDDY.md
本文件为 CodeBuddy Code 在本仓库中工作时提供指导。
## 构建与运行命令
| 操作 | 命令 |
|---|---|
| 构建 | `go build -o tmp/main .` |
| 运行 | `go run .` |
| Wire 代码生成 | `go generate ./...`(修改 `wire.go` 后必须运行) |
| 整理依赖 | `go mod tidy` |
| 测试 | `go test ./...`(暂无测试文件) |
应用启动端口为 8000配置在 `config/config.dev.yml`)。环境由 `.env` 控制(`ENV=dev` 对应 `config/config.{env}.yml`)。
## 架构
Go 后端 API使用 Gin + MongoDB + Wire 依赖注入。经典三层架构DTO/DO/PO 模型分离。
### 请求流程
```
Client → Gin Router → wrap.Wrap[R,P](绑定/校验/响应)→ API Handler → Service → Repo → MongoDB
```
### 各层职责
- **API**`api/`路由、中间件、HTTP 处理器。`wrap.Wrap[R,P]()` 泛型包装器统一处理 JSON 绑定、参数校验gookit/validate和统一响应格式`Resp{code, msg, data, ok, time}`)。
- **Service**`service/`业务逻辑。Wire 注入集定义在 `service.go`
- **Repo**`repo/`):数据访问。`BaseRepo[T]` 泛型仓储提供 CRUD 操作,支持软删除和租户隔离。子类添加实体特定查询。
- **Model**`model/`
- `dto/` — API 请求/响应结构体
- `do/` — Service 层输入/输出结构体
- `po/` — 数据库实体,均嵌入 `TBase`OID、时间戳、创建人、tenantId
### 关键设计模式
- **多租户隔离**`BaseRepo.RawProcessFilter` 自动从 context 注入 `tenantId`(通过 `sctx` 包)。所有 PO 实体继承 `TBase.Tenant_OID`
- **Wire 依赖注入**`wire.go`(构建标签 `wireinject`)定义注入图,`wire_gen.go` 为自动生成代码。注入链:`Configuration → MongoDb → Repos → Services → APIs → Router → Engine`
- **泛型 wrap 处理器**`wrap.Wrap[R, P]()` 将请求绑定到 R校验后调用 `func(context.Context, *R) (*P, error)`,成功返回 `Ok(c, data)`,失败返回 `Err(c, err)`
- **错误码**:系统错误定义在 `common/errsys.go`0=成功50-53=内部错误s0xxx=业务通用),用户错误定义在 `common/erruser.go`u001-u004
### API 路由
```
GET / → Hello World
POST /api/v1/login → 用户登录(需 tenantNo + userName + password
POST /api/v1/register → 用户注册
GET /api/v1/user/current → 获取当前用户信息(需认证)
```
### 配置加载
1. `.env` 设置 `ENV` 变量
2. 通过 Viper 加载 `config/config.{ENV}.yml`
3. 详见 `core/config.go` 中的 `Configuration` 结构体和默认值
## 开发约定
- 修改 `wire.go` 后,务必运行 `go generate ./...` 重新生成 `wire_gen.go`
- 新增 API 端点:在 `model/dto/` 定义 DTO`api/v1/` 添加处理器,在 `api/api.go` 注册路由,实现 service 方法,按需添加 repo 方法。
- 新增实体:在 `model/po/` 创建 PO嵌入 `TBase`),在 `model/do/` 创建 DO创建 `XxxRepo` 继承 `BaseRepo[T]`,添加 Wire provider。
- 新增错误码:按现有模式在 `common/errsys.go``common/erruser.go` 中添加业务错误。