AGENT SKILL

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

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-patterns skill takes precedence.

Go Design Patterns & Idioms

Best Practices Summary

  1. Constructors SHOULD use functional options — scale as APIs evolve (one function per option, no breaking changes)
  2. Functional options MUST return an error if validation can fail — catch bad config at construction, not runtime
  3. Avoid init() — implicit, cannot return errors, makes tests unpredictable. Use explicit constructors
  4. Enums SHOULD start at 1 (or Unknown sentinel at 0) — Go's zero value silently passes as first member
  5. Error cases MUST be handled first with early return — keep happy path flat → see samber/cc-skills-golang@golang-code-style
  6. Panic is for bugs, not expected errors — callers handle returned errors; panics crash process
  7. defer Close() immediately after opening — later edits can skip cleanup
  8. runtime.AddCleanup over runtime.SetFinalizer — finalizers are unpredictable, can resurrect objects
  9. Every external call SHOULD have a timeout — slow upstream hangs goroutine indefinitely
  10. Limit everything (pool sizes, queue depths, buffers) — unbounded resources grow until crash
  11. Retry logic MUST check context cancellation between attempts
  12. Use strings.Builder for concatenation in loops → see samber/cc-skills-golang@golang-code-style
  13. string vs []byte: use []byte for mutation and I/O, string for display and keys — conversions allocate
  14. Iterators (Go 1.23+): use for lazy evaluation — avoid loading everything into memory
  15. Stream large transfers — loading millions of rows causes OOM; streaming keeps memory constant
  16. //go:embed for static assets — embedded at compile time, no runtime file I/O errors
  17. Use crypto/rand for keys/tokens — math/rand is predictable → see samber/cc-skills-golang@golang-security
  18. Regexp MUST be compiled once at package level — compilation is O(n), allocates
  19. Compile-time interface checks: var _ Interface = (*Type)(nil) → see samber/cc-skills-golang@golang-structs-interfaces
  20. A little recode > a big dependency — each dep adds attack surface, maintenance burden
  21. 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 use defer 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-structures skill for data structure selection, internals, container/ packages
  • → See samber/cc-skills-golang@golang-error-handling skill for error wrapping, sentinel errors, single handling rule
  • → See samber/cc-skills-golang@golang-structs-interfaces skill for interface design and composition
  • → See samber/cc-skills-golang@golang-concurrency skill for goroutine lifecycle and graceful shutdown
  • → See samber/cc-skills-golang@golang-context skill for timeout and cancellation patterns
  • → See samber/cc-skills-golang@golang-project-layout skill for architecture and directory structure
  • → See samber/cc-skills-golang@golang-refactoring skill to safely stage migration toward one of these patterns (options struct, DI, consumer-side interfaces) across existing codebase

04 同仓库更多 Skills

w0rxbend
w0rxbend/dot-agents

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.

★ 0
w0rxbend
w0rxbend/dot-agents

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.

★ 0
w0rxbend
w0rxbend/dot-agents

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.

★ 0
w0rxbend
w0rxbend/dot-agents

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.

★ 0
w0rxbend
w0rxbend/dot-agents

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.

★ 0
w0rxbend
w0rxbend/dot-agents

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.

★ 0