Files
digital-psychology/apps/docs/standards/02-go.md
T
jackyu66gitandCursor 2fb1dfee14 chore: seal Design Vision v1 and monorepo scaffold
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>
2026-08-02 16:00:44 +08:00

1.5 KiB
Raw Blame History

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(或真正的调用包)定义 interfaceservice 实现之。
避免在 service 包里堆 interface.go 再反向依赖。

Context

所有可能阻塞或下游调用的方法,首参必须是 context.Context

func (s *Service) Login(ctx context.Context, req LoginRequest) (*User, error)

错误

if err != nil {
    return fmt.Errorf("create user: %w", err)
}

禁止裸 return err 且丢失上下文;禁止 _ = err 吞掉关键错误。

日志

结构化日志(zap 或统一 slog 封装)。禁止业务路径 fmt.Println

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。