golang-design-patterns
Design Go APIs with functional options, interfaces, composition, constructors, and clear ownership. Select a pattern for a concrete design problem rather than adding abstractions by default.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- golang-design-patterns
- paths
- [ "**/*.go" ]
- license
- MIT
- metadata
- { "author": "samber", "version": "1.2.1", "openclaw": { "emoji": "🏗", "install": [], "homepage": "https://github.com/samber/cc-skills-golang", "requires": { "bins": [ "go" ] } } }
- description
- Design Go APIs with functional options, interfaces, composition, constructors, and clear ownership. Select a pattern for a concrete design problem rather than adding abstractions by default.
- allowed-tools
- Read Edit Write Glob Grep Bash(go build:*) Bash(go test:*) Bash(go vet:*) Bash(golangci-lint run:*) Bash(git status:*) Bash(git diff:*) Bash(git log:*) Bash(git show:*) Agent AskUserQuestion
- compatibility
- Designed for Claude Code, Codex or similar harness, and for projects using Golang.
- user-invocable
- true
02 资源文件 7
- 参考文档evals/evals.json22.1 KB
- 参考文档references/architecture.md4.9 KB
- 参考文档references/clean-architecture.md5.4 KB
- 参考文档references/data-handling.md1.5 KB
- 参考文档references/ddd.md6.9 KB
- 参考文档references/hexagonal-architecture.md6.7 KB
- 参考文档references/resource-management.md4.1 KB
03 SKILL.md 正文
Persona: Go architect who values simplicity and explicitness. Apply patterns only when they solve real problem, not to show sophistication. Push back on premature abstraction.
Modes:
- Design mode — new APIs, packages, application structure: ask developer's architecture preference before proposing patterns; favor smallest pattern meeting requirement.
- Review mode — audit existing code: scan for
init()abuse, unbounded resources, missing timeouts, implicit global state; report findings before suggesting refactors.
Community default. Company skill that explicitly supersedes
samber/cc-skills-golang@golang-design-patternsskill takes precedence.
Go Design Patterns & Idioms
Best Practices Summary
- Constructors SHOULD use functional options — scale as APIs evolve (one function per option, no breaking changes)
- Functional options MUST return an error if validation can fail — catch bad config at construction, not runtime
- Avoid
init()— implicit, cannot return errors, makes tests unpredictable. Use explicit constructors - Enums SHOULD start at 1 (or Unknown sentinel at 0) — Go's zero value silently passes as first member
- Error cases MUST be handled first with early return — keep happy path flat → see
samber/cc-skills-golang@golang-code-style - Panic is for bugs, not expected errors — callers handle returned errors; panics crash process
defer Close()immediately after opening — later edits can skip cleanupruntime.AddCleanupoverruntime.SetFinalizer— finalizers are unpredictable, can resurrect objects- Every external call SHOULD have a timeout — slow upstream hangs goroutine indefinitely
- Limit everything (pool sizes, queue depths, buffers) — unbounded resources grow until crash
- Retry logic MUST check context cancellation between attempts
- Use
strings.Builderfor concatenation in loops → seesamber/cc-skills-golang@golang-code-style - string vs []byte: use
[]bytefor mutation and I/O,stringfor display and keys — conversions allocate - Iterators (Go 1.23+): use for lazy evaluation — avoid loading everything into memory
- Stream large transfers — loading millions of rows causes OOM; streaming keeps memory constant
//go:embedfor static assets — embedded at compile time, no runtime file I/O errors- Use
crypto/randfor keys/tokens —math/randis predictable → seesamber/cc-skills-golang@golang-security - Regexp MUST be compiled once at package level — compilation is O(n), allocates
- Compile-time interface checks:
var _ Interface = (*Type)(nil)→ seesamber/cc-skills-golang@golang-structs-interfaces - A little recode > a big dependency — each dep adds attack surface, maintenance burden
- Design for testability — accept interfaces, inject dependencies, keep functions pure
Constructor Patterns: Functional Options vs Builder
Functional Options (Preferred)
type Server struct {
addr string
readTimeout time.Duration
writeTimeout time.Duration
maxConns int
}
type Option func(*Server)
func WithReadTimeout(d time.Duration) Option {
return func(s *Server) { s.readTimeout = d }
}
func WithWriteTimeout(d time.Duration) Option {
return func(s *Server) { s.writeTimeout = d }
}
func WithMaxConns(n int) Option {
return func(s *Server) { s.maxConns = n }
}
func NewServer(addr string, opts ...Option) *Server {
// Default options
s := &Server{
addr: addr,
readTimeout: 5 * time.Second,
writeTimeout: 10 * time.Second,
maxConns: 100,
}
for _, opt := range opts {
opt(s)
}
return s
}
// Usage
srv := NewServer(":8080",
WithReadTimeout(30*time.Second),
WithMaxConns(500),
)
If option can be invalid, make option type return error; constructor returns it (rule 2):
type Option func(*Server) error
func WithMaxConns(n int) Option {
return func(s *Server) error {
if n <= 0 {
return fmt.Errorf("max conns must be positive, got %d", n)
}
s.maxConns = n
return nil
}
}
func NewServer(addr string, opts ...Option) (*Server, error) {
s := &Server{addr: addr, readTimeout: 5 * time.Second, writeTimeout: 10 * time.Second, maxConns: 100}
for _, opt := range opts {
if err := opt(s); err != nil {
return nil, fmt.Errorf("new server: %w", err)
}
}
return s, nil
}
Use builder pattern only for complex validation between configuration steps.
Constructors & Initialization
Avoid init() and Mutable Globals
init() runs implicitly, hinders testing, creates hidden dependencies:
- Multiple
init()functions run in declaration order, across files in filename alphabetical order — fragile - Cannot return errors — failures must panic or
log.Fatal - Runs before
main()and tests — side effects make tests unpredictable
// Bad — hidden global state
var db *sql.DB
func init() {
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
}
// Good — explicit initialization, injectable
func NewUserRepository(db *sql.DB) *UserRepository {
return &UserRepository{db: db}
}
Enums: Start at 1
type Status int
const (
StatusUnknown Status = iota // 0 = invalid/unset
StatusActive // 1
StatusInactive // 2
StatusSuspended // 3
)
Compile Regexp Once
// Good — compiled once at package level
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
func ValidateEmail(email string) bool {
return emailRegex.MatchString(email)
}
Use //go:embed for Static Assets
import "embed"
//go:embed templates/*
var templateFS embed.FS
//go:embed version.txt
var version string
Error Flow Patterns
When to Panic vs Return Error
- Return error: network failures, file not found, invalid input — anything caller can handle
- Panic: nil pointer where it should be impossible, violated invariant,
Must*constructors used at init time .Close()/Flush()errors: read-only cleanup can often usedefer f.Close(); write/flush resources must report close or flush errors when durability matters
Data Handling
string vs []byte vs []rune
| Type | Default for | Use when |
|---|---|---|
string |
Everything | Immutable, safe, UTF-8 |
[]byte |
I/O | Writing to io.Writer, building strings, mutations |
[]rune |
Unicode ops | len() must mean characters, not bytes |
Avoid repeated conversions — each allocates. Stay in one type until you need the other.
Iterators & Streaming for Large Data
Code examples: Data Handling Patterns.
Resource Management
defer Close() examples, graceful shutdown, resource pools and runtime.AddCleanup: see Resource Management.
Resilience & Limits
Timeout Every External Call
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
resp, err := httpClient.Do(req.WithContext(ctx))
Retry & Context Checks
Retry logic MUST check ctx.Err() between attempts and use exponential/linear backoff via select on ctx.Done(). Long loops MUST check ctx.Err() periodically. → See samber/cc-skills-golang@golang-context skill.
Database Patterns
→ See samber/cc-skills-golang@golang-database skill for sqlx/pgx, transactions, nullable columns, connection pools, repository interfaces, testing.
Architecture
Ask developer's preferred architecture: clean architecture, hexagonal, DDD, or flat layout. Don't impose complex architecture on small project.
Core principles regardless of architecture (details: Architecture Patterns):
- Keep domain pure — no framework dependencies in domain layer
- Fail fast — validate at boundaries, trust internal code
- Make illegal states unrepresentable — use types to enforce invariants
- Respect 12-factor app principles → see
samber/cc-skills-golang@golang-project-layout
Detailed Guides
| Guide | Scope |
|---|---|
| Architecture Patterns | High-level principles, when each architecture fits |
| Clean Architecture | Use cases, dependency rule, layered adapters |
| Hexagonal Architecture | Ports and adapters, domain core isolation |
| Domain-Driven Design | Aggregates, value objects, bounded contexts |
Cross-References
- → See
samber/cc-skills-golang@golang-data-structuresskill for data structure selection, internals, container/ packages - → See
samber/cc-skills-golang@golang-error-handlingskill for error wrapping, sentinel errors, single handling rule - → See
samber/cc-skills-golang@golang-structs-interfacesskill for interface design and composition - → See
samber/cc-skills-golang@golang-concurrencyskill for goroutine lifecycle and graceful shutdown - → See
samber/cc-skills-golang@golang-contextskill for timeout and cancellation patterns - → See
samber/cc-skills-golang@golang-project-layoutskill for architecture and directory structure - → See
samber/cc-skills-golang@golang-refactoringskill to safely stage migration toward one of these patterns (options struct, DI, consumer-side interfaces) across existing codebase
04 同仓库更多 Skills
wiki-builder
Create and maintain a local Markdown research wiki (sources with provenance, compiled concept/source pages, index, maintenance log) driven by a per-wiki config. Use when the user wants to start a wiki or knowledge base, ingest sources into one, or query and update it; use wiki-page-writer for a single code deep-dive page.
refactoring-guru
Diagnose a named code smell and apply the smallest behavior-preserving refactoring, with verification before and after and an explicit stop condition. Use for structural refactors (extract, move, consolidate, change ownership), not for feature or bug work; for readability cleanup of recent changes use code-simplification.
legacy-seams
When changing untested legacy code, pin the observed results with characterization tests and open the smallest seam that substitutes only the blocking dependency, separate from any later logic change. Use when a clock, random source, I/O, global, or hidden constructor blocks a test or a safe edit. Use test-driven-development for a new behavior or a bug, refactoring-guru for one named structural refactor after the seam exists, and code-refactoring-tech-debt to choose which legacy to replace.
idea-refine
Refine a raw idea into a one-page brief (problem statement, recommended direction, assumptions to validate, MVP scope, not-doing list) through divergent then convergent thinking. Use when an idea is still vague or you want options and a stress test before committing; use interview-me when the goal itself is unclear and spec-driven-development once the direction is chosen.
code-review-and-quality
Review rubric and approval standard for any change before merge, including code written by you, another agent, or a human: five axes (correctness, readability, architecture, security, performance), change sizing, structural remedies, severity labels, and feedback technique. Use to judge whether a change is fit to merge; use code-review to run a PR or diff review end to end.
code-perfection
Smell and style gate for code you write or change. Bans known code smells (long method, large class, primitive obsession, long parameter list, data clumps, duplicate code, dead code, feature envy, shotgun surgery, flag arguments, message chains) and enforces behavior-preserving structure. On Scala files, enforces worxbend style. Use while implementing, reviewing a diff for smells, or when a smell or style violation is suspected. Routine construction stays with code-complete. SOLID and DRY stay with clean-code-guard. One named structural refactor stays with refactoring-guru.