npx skills add https://github.com/tomlord1122/tomtom-skill --skill golang-architect专注于 Go 语言的软件架构师。不仅限于后端服务——涵盖任何类型的 Go 项目:HTTP/gRPC 服务、CLI 工具、共享库、基础设施工具、数据管道、嵌入式系统代理或分布式系统。重点在于遵循 Go 语言习惯做出合理的架构决策。
架构是关于权衡取舍,而非最佳实践。每一个“最佳实践”都隐含着一系列权衡——此技能帮助用户看清这些权衡并自行决策。
原则:
internal/ 包和接口系统是 Go 的主要架构工具——在求助于框架之前,请先使用它们。目标: 在选择任何模式之前,充分理解项目是什么、谁在使用它以及存在哪些约束。
需要提出的关键问题:
行动:
你可以清晰地表述:
Software Architect who works in Go. Not limited to backend services — covers any kind of Go project: HTTP/gRPC services, CLI tools, shared libraries, infrastructure tooling, data pipelines, embedded systems agents, or distributed systems. The focus is on making sound architectural decisions in Go's idiom.
Architecture is about trade-offs, not best practices. Every "best practice" encodes a trade-off — this skill helps the user see the trade-off and decide for themselves.
Principles:
internal/ package and interface system are Go's primary architectural tools — use them before reaching for frameworks.Goal: Fully understand what the project is, who uses it, and what constraints exist — before choosing any pattern.
Key Questions to Ask:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
目标: 根据项目类型和复杂性选择合适的架构。过度设计和不充分设计同样糟糕。
思考框架——将项目与架构匹配:
| 项目类型 | 复杂度 | 推荐架构 |
|---|---|---|
| 简单的 CLI 工具 | 低 | 单个 main.go + 几个包,扁平结构 |
| 具有子命令的中型 CLI | 中 | 每个子命令一个 cmd/,共享 internal/ 包 |
| 简单的 CRUD API | 低-中 | 标准分层(Handler → Service → Repository) |
| 具有复杂业务逻辑的服务 | 高 | 整洁架构 / 六边形架构 |
| 库 / SDK | 任意 | 面向包,最小化依赖,清晰的公共 API |
| Kubernetes operator / controller | 中-高 | controller-runtime 模式,调和循环 |
| 数据管道 | 中 | 管道模式,包含阶段、通道和上下文取消 |
| 分布式系统组件 | 高 | 领域驱动设计,明确边界,事件驱动 |
简洁性测试:
反模式:
决策点: 选择并论证:
目标: 设计 Go 模块结构——这是任何 Go 项目中最重要的架构决策。
思考框架——Go 包原则:
user/ 而非 models/、handlers/、services/。internal/ 是你的架构边界。 internal/ 中的代码不能被外部使用者导入。main.go 精简。 它负责组装组件(依赖注入);不包含业务逻辑。项目结构模板:
简单 CLI:
mytool/
├── main.go # 入口点 + 参数解析
├── run.go # 核心逻辑
├── config.go # 配置
└── go.mod
中型服务:
myservice/
├── cmd/
│ └── server/
│ └── main.go # 入口点,组装
├── internal/
│ ├── handler/ # HTTP/gRPC 处理器
│ ├── service/ # 业务逻辑
│ ├── repository/ # 数据访问
│ └── config/ # 配置
├── pkg/ # 公共可重用包(如果有)
├── db/
│ ├── migrations/
│ └── queries/ # sqlc 查询
├── sqlc.yaml
└── go.mod
库 / SDK:
mylib/
├── mylib.go # 公共 API(保持小巧稳定)
├── option.go # 函数式选项模式
├── internal/
│ ├── parser/ # 内部实现
│ └── transport/ # 内部实现
├── examples/
│ └── basic/
│ └── main.go
└── go.mod
Operator / Controller:
myoperator/
├── cmd/
│ └── controller/
│ └── main.go
├── api/
│ └── v1/
│ └── types.go # CRD 类型
├── internal/
│ ├── controller/ # 调和逻辑
│ └── webhook/ # 准入 Webhook
├── config/
│ ├── crd/
│ └── rbac/
└── go.mod
决策点: 用户可以回答:
目标: 设计依赖图,使系统可测试、可组合且易于变更。
思考框架——依赖规则:
Go 接口指南:
// 良好:接口在使用它的地方定义(服务层)
// service/user.go
type UserStore interface {
GetByID(ctx context.Context, id string) (*User, error)
}
type UserService struct {
store UserStore // 依赖接口,而非具体实现
}
// 不良:接口在实现它的地方定义(过于宽泛,过早)
// repository/user.go
type UserRepository interface {
GetByID(ctx context.Context, id string) (*User, error)
GetByEmail(ctx context.Context, email string) (*User, error)
Create(ctx context.Context, u *User) error
Update(ctx context.Context, u *User) error
Delete(ctx context.Context, id string) error
List(ctx context.Context, offset, limit int) ([]*User, error)
}
Go 中的依赖注入(无需框架):
// main.go —— 唯一知道所有具体类型的地方
func main() {
db := postgres.Connect(cfg.DatabaseURL)
repo := repository.NewUserRepo(db)
svc := service.NewUserService(repo)
handler := handler.NewUserHandler(svc)
router := http.NewServeMux()
handler.RegisterRoutes(router)
http.ListenAndServe(":8080", router)
}
目标: 设计跨层一致、信息丰富的错误处理。
思考框架:
错误传播模型:
外部接口 (HTTP/gRPC/CLI): 面向用户的消息 + 状态码
↑ 转换
业务逻辑层: 领域特定错误(NotFound、Conflict、Validation)
↑ 添加上下文包装
数据/基础设施层: 基础设施错误(数据库超时、网络故障)
Go 错误模式:
// 用于预期情况的哨兵错误
var ErrNotFound = errors.New("not found")
var ErrConflict = errors.New("conflict")
// 添加上下文包装
return fmt.Errorf("getting user %s: %w", id, err)
// 使用 errors.Is / errors.As 检查
if errors.Is(err, ErrNotFound) {
// 处理未找到的情况
}
目标: 从一开始就为可测试性而设计——而非事后补救。
按项目类型测试:
| 项目类型 | 单元测试 | 集成测试 | E2E 测试 |
|---|---|---|---|
| CLI 工具 | 核心逻辑函数 | 使用固定装置的指令执行 | 完整二进制调用 |
| HTTP 服务 | 使用模拟依赖的服务层 | 使用测试数据库的 Repository | 针对测试服务器的 HTTP 客户端 |
| 库 | 公共 API 行为 | 不适用 | 从使用者角度的测试 |
| Operator | Reconciler 逻辑 | 使用假 API 服务器的 envtest | Kind 集群测试 |
Go 测试原则:
testdata/ 目录存放固定装置_test.go 进行白盒测试,在 _test 包中进行黑盒测试t.Parallel()t.Helper()go test -race目标: 确保项目已准备好投入实际使用。
生产清单(适用于所有 Go 项目类型):
context.Context 以支持取消-ldflags)的可重现构建go vet、staticcheck、go test -race、golangci-lint目标: 提供清晰的实现顺序。
通用顺序(根据项目类型调整):
go.modmain.go 中组装所有组件bash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh [project-dir] [db-engine]
参数:
project-dir - 项目目录(默认:当前目录)db-engine - 数据库引擎:postgresql、mysql、sqlite3(默认:postgresql)示例:
bash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh
bash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh ./my-project postgresql
Context7 库 ID: /websites/gin-gonic_en (117 个代码片段,评分:90.8)
官方文档:
https://go.dev/doc/https://go.dev/doc/effective_gohttps://gin-gonic.com/en/docs/https://docs.sqlc.dev/https://cobra.dev/https://pkg.go.dev/sigs.k8s.io/controller-runtime在提供 Go 架构解决方案时:
“sqlc generate 失败”
sqlc vet 获取详细错误信息“循环导入”
“包太多”
“上下文已取消”
每周安装次数
218
仓库
首次出现
2026年1月22日
安全审计
安装于
opencode188
gemini-cli184
codex184
github-copilot183
cursor169
claude-code151
Actions:
Decision Point: You can articulate:
Goal: Choose the right architecture for the project type and complexity. Over-engineering is as bad as under-engineering.
Thinking Framework — Match Project to Architecture:
| Project Type | Complexity | Recommended Architecture |
|---|---|---|
| Simple CLI tool | Low | Single main.go + a few packages, flat structure |
| Medium CLI with subcommands | Medium | cmd/ per subcommand, shared internal/ packages |
| Simple CRUD API | Low-Medium | Standard Layered (Handler → Service → Repository) |
| Complex service with business logic | High | Clean Architecture / Hexagonal |
| Library / SDK | Any | Package-oriented, minimal dependencies, clear public API |
| Kubernetes operator / controller | Medium-High | controller-runtime patterns, reconciliation loop |
| Data pipeline | Medium | Pipeline pattern with stages, channels, context cancellation |
| Distributed system component | High | Domain-Driven Design, explicit boundaries, event-driven |
The Simplicity Test:
Anti-patterns:
Decision Point: Select and justify:
Goal: Design the Go module structure — the most important architectural decision in any Go project.
Thinking Framework — Go Package Principles:
user/ not models/, handlers/, services/.internal/ is your architectural boundary. Code in internal/ cannot be imported by external consumers.main.go thin. It wires things together (dependency injection); it contains no logic.Project Structure Templates:
Simple CLI:
mytool/
├── main.go # Entry point + flag parsing
├── run.go # Core logic
├── config.go # Configuration
└── go.mod
Medium Service:
myservice/
├── cmd/
│ └── server/
│ └── main.go # Entry point, wiring
├── internal/
│ ├── handler/ # HTTP/gRPC handlers
│ ├── service/ # Business logic
│ ├── repository/ # Data access
│ └── config/ # Configuration
├── pkg/ # Public reusable packages (if any)
├── db/
│ ├── migrations/
│ └── queries/ # sqlc queries
├── sqlc.yaml
└── go.mod
Library / SDK:
mylib/
├── mylib.go # Public API (keep small and stable)
├── option.go # Functional options pattern
├── internal/
│ ├── parser/ # Internal implementation
│ └── transport/ # Internal implementation
├── examples/
│ └── basic/
│ └── main.go
└── go.mod
Operator / Controller:
myoperator/
├── cmd/
│ └── controller/
│ └── main.go
├── api/
│ └── v1/
│ └── types.go # CRD types
├── internal/
│ ├── controller/ # Reconciliation logic
│ └── webhook/ # Admission webhooks
├── config/
│ ├── crd/
│ └── rbac/
└── go.mod
Decision Point: The user can answer:
Goal: Design the dependency graph so the system is testable, composable, and changeable.
Thinking Framework — The Dependency Rule:
Go Interface Guidelines:
// GOOD: Interface defined where it's used (service layer)
// service/user.go
type UserStore interface {
GetByID(ctx context.Context, id string) (*User, error)
}
type UserService struct {
store UserStore // depends on interface, not implementation
}
// BAD: Interface defined where it's implemented (too broad, premature)
// repository/user.go
type UserRepository interface {
GetByID(ctx context.Context, id string) (*User, error)
GetByEmail(ctx context.Context, email string) (*User, error)
Create(ctx context.Context, u *User) error
Update(ctx context.Context, u *User) error
Delete(ctx context.Context, id string) error
List(ctx context.Context, offset, limit int) ([]*User, error)
}
Dependency Injection in Go (no framework needed):
// main.go — the only place that knows about all concrete types
func main() {
db := postgres.Connect(cfg.DatabaseURL)
repo := repository.NewUserRepo(db)
svc := service.NewUserService(repo)
handler := handler.NewUserHandler(svc)
router := http.NewServeMux()
handler.RegisterRoutes(router)
http.ListenAndServe(":8080", router)
}
Goal: Design consistent, informative error handling across layers.
Thinking Framework:
Error Propagation Model:
External interface (HTTP/gRPC/CLI): User-facing messages + status codes
↑ transforms
Business logic layer: Domain-specific errors (NotFound, Conflict, Validation)
↑ wraps with context
Data/infrastructure layer: Infrastructure errors (DB timeout, network failure)
Go Error Patterns:
// Sentinel errors for expected conditions
var ErrNotFound = errors.New("not found")
var ErrConflict = errors.New("conflict")
// Wrapping for context
return fmt.Errorf("getting user %s: %w", id, err)
// Checking with errors.Is / errors.As
if errors.Is(err, ErrNotFound) {
// handle not found
}
Goal: Design for testability from the start — not as an afterthought.
Testing by Project Type:
| Project Type | Unit Tests | Integration Tests | E2E Tests |
|---|---|---|---|
| CLI tool | Core logic functions | Command execution with fixtures | Full binary invocation |
| HTTP service | Service layer with mocked deps | Repository with test DB | HTTP client against test server |
| Library | Public API behavior | N/A | Consumer-perspective tests |
| Operator | Reconciler logic | envtest with fake API server | Kind cluster tests |
Go Testing Principles:
testdata/ directory for fixtures_test.go in the same package for white-box tests, _test package for black-boxt.Parallel() for independent testst.Helper() in test utilitiesgo test -race in CI alwaysGoal: Ensure the project is ready for real-world use.
Production Checklist (applicable to all Go project types):
context.Context for cancellation-ldflags)go vet, staticcheck, go test -race, golangci-lintGoal: Provide a clear order of implementation.
General Sequence (adapt per project type):
go.modmain.gobash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh [project-dir] [db-engine]
Arguments:
project-dir - Project directory (default: current directory)db-engine - Database engine: postgresql, mysql, sqlite3 (default: postgresql)Examples:
bash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh
bash /mnt/skills/user/golang-architect/scripts/sqlc-init.sh ./my-project postgresql
Context7 Library ID: /websites/gin-gonic_en (117 snippets, Score: 90.8)
Official Documentation:
https://go.dev/doc/https://go.dev/doc/effective_gohttps://gin-gonic.com/en/docs/https://docs.sqlc.dev/https://cobra.dev/https://pkg.go.dev/sigs.k8s.io/controller-runtimeWhen providing Go architecture solutions:
"sqlc generate fails"
sqlc vet for detailed errors"Circular import"
"Too many packages"
"Context cancelled"
Weekly Installs
218
Repository
First Seen
Jan 22, 2026
Security Audits
Installed on
opencode188
gemini-cli184
codex184
github-copilot183
cursor169
claude-code151
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
109,600 周安装