Archive the differentiated YuXinGu product docs, AI engineering system, design contract, and Go/Vue scaffold. Next execution prioritizes Cece-parity over early innovation (see .ai/product/STRATEGY.md). Co-authored-by: Cursor <cursoragent@cursor.com>
67 lines
1.5 KiB
Markdown
67 lines
1.5 KiB
Markdown
# 02 Go 编码规范
|
||
|
||
参考:Effective Go、Uber Go Style Guide、Google Go Style Guide。
|
||
|
||
## 目录
|
||
|
||
```
|
||
apps/api/
|
||
cmd/server/
|
||
internal/
|
||
handler/
|
||
service/<domain>/ # auth, profile, report, order…
|
||
repository/
|
||
model/
|
||
middleware/
|
||
config/
|
||
pkg/ # 可复用小库,禁止膨胀
|
||
migrations/
|
||
```
|
||
|
||
## 包职责
|
||
|
||
- 按 **业务域** 分包,不要 `package utils`。
|
||
- 好:`order` `payment` `auth` `profile`。
|
||
- `pkg/` 仅放与业务无关的通用能力(如 `response` 封装)。
|
||
|
||
## Interface 放在调用方
|
||
|
||
在 `handler`(或真正的调用包)定义 interface,service 实现之。
|
||
避免在 service 包里堆 `interface.go` 再反向依赖。
|
||
|
||
## Context
|
||
|
||
所有可能阻塞或下游调用的方法,首参必须是 `context.Context`:
|
||
|
||
```go
|
||
func (s *Service) Login(ctx context.Context, req LoginRequest) (*User, error)
|
||
```
|
||
|
||
## 错误
|
||
|
||
```go
|
||
if err != nil {
|
||
return fmt.Errorf("create user: %w", err)
|
||
}
|
||
```
|
||
|
||
禁止裸 `return err` 且丢失上下文;禁止 `_ = err` 吞掉关键错误。
|
||
|
||
## 日志
|
||
|
||
结构化日志(zap 或统一 slog 封装)。禁止业务路径 `fmt.Println`。
|
||
|
||
```go
|
||
logger.Info("user login", zap.Int64("uid", uid), zap.String("ip", ip))
|
||
```
|
||
|
||
## 命名
|
||
|
||
- 文件:`snake` 不强制,Go 惯用短名;导出标识符 PascalCase。
|
||
- 避免 `Manager` `Helper` `Util` 空泛命名。
|
||
|
||
## 测试
|
||
|
||
- `*_test.go` 与实现同包或 `package foo_test`。
|
||
- 表驱动测试优先;外部依赖用 interface mock。
|