Files
pig-farm-controller/design/provide-logger-with-mothed/task-middleware.md
2025-11-05 18:38:41 +08:00

26 lines
2.1 KiB
Markdown
Raw 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.

- **`internal/app/middleware/auth.go`**
- **中间件函数改造 (`AuthMiddleware`)**:
- [x] 在 `AuthMiddleware` 返回的 `echo.HandlerFunc` 内部,获取 `echo.Context``request.Context()` 作为
`upstreamCtx`
- [x] 使用 `newCtx, logger := logs.Trace(upstreamCtx, context.Background(), "AuthMiddleware")` 来创建 `newCtx`
`logger` 实例。
- [x] 使用 `c.SetRequest(c.Request().WithContext(newCtx))` 将更新后的 `newCtx` 写入 `echo.Context`,以便后续处理链使用。
- [x] 将所有对 `controller.SendErrorWithStatus` 的调用替换为 `controller.SendErrorWithAudit`
- [x] 确保 `controller.SendErrorWithAudit` 接收 `newCtx` 作为第一个参数,并提供适当的 `actionType`,
`description`, `targetResource`
- 例如,对于“请求未包含授权标头”的错误,`actionType` 可以是“认证失败”,`description` 是“请求未包含授权标头”,
`targetResource``nil`
- 对于“无效的Token”错误`actionType` 可以是“认证失败”,`description` 是“无效的Token”`targetResource`
`tokenString`
- [x] 在 `AuthMiddleware` 内部,如果需要日志记录(例如 `tokenService.ParseToken` 失败或 `userRepo.FindByID`
失败),使用新创建的 `logger` 实例进行日志输出。
- [x] **关键**: 使用 `c.SetRequest(c.Request().WithContext(newCtx))` 将更新后的 `Context` 写回 `echo.Context`
,以便传递给后续的中间件和 `Controller`
- **`internal/app/middleware/audit.go`**
- **改造动作**:
- [x] 检查并重构所有日志记录中间件。
- [x] 中间件应该从请求的 `c.Request().Context()` 中提取 `upstreamCtx`
- [x] 使用 `logs.Trace``logs.AddFuncName` 创建新的 `Context``Logger`
- [x] **关键**: 使用 `c.SetRequest(c.Request().WithContext(newCtx))` 将更新后的 `Context` 写回 `echo.Context`
,以便传递给后续的中间件和 `Controller`