# Golang Design Patterns

> Select or review idiomatic Go patterns for constructors, configuration, lifecycle, resilience, streaming, data flow, and package boundaries. Use when an implementation needs an explicit design trade-off rather than a routine local edit.

- Skill: `reagin/golang-design-patterns` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add reagin/golang-design-patterns`
- Raw SKILL.md: https://api.skillmd.com/api/skills/reagin/golang-design-patterns/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: MIT
- Author: reagin (https://skillmd.com/u/reagin)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/reagin/golang-design-patterns

---


# Go Design Patterns

Use the smallest pattern that resolves a demonstrated pressure. Go APIs benefit more from explicit ownership and stable contracts than from naming every familiar object-oriented pattern.

## Understand the existing design

Before proposing or implementing a pattern:

1. Read repository instructions, `go.mod`, package layout, constructors, public APIs, and tests.
2. Identify the actual pressure: optional configuration, lifecycle ownership, boundary isolation, multiple implementations, unbounded work, or data volume.
3. Record compatibility constraints and real callers. Do not redesign the package around a hypothetical future use.
4. Prefer the repository's established pattern when it already handles the requirement cleanly.
5. Keep review and implementation scope separate, and report broader design opportunities independently from the requested change.

## Construction and configuration

| Shape | Use when | Avoid when |
| --- | --- | --- |
| Direct arguments | Few required values with clear meaning | Several adjacent values are easy to swap or evolve together |
| Config struct | Configuration is cohesive, validated together, or loaded externally | It obscures a tiny stable API |
| Functional options | A public constructor has genuinely optional, orthogonal settings and compatibility matters | Options hide required dependencies or permit invalid intermediate state |
| Builder | Construction is staged and the intermediate choices need validation or fluent domain language | It adds ceremony to ordinary initialization |

Functional options are one choice, not the default for every constructor. Keep required dependencies explicit. If applying an option can fail, return that failure during construction and leave no partially initialized object.

```go
type Option func(*Server) error

func NewServer(store Store, opts ...Option) (*Server, error) {
    s := &Server{store: store, timeout: defaultTimeout}
    for _, apply := range opts {
        if err := apply(s); err != nil {
            return nil, fmt.Errorf("applying server option: %w", err)
        }
    }
    if err := s.validate(); err != nil {
        return nil, err
    }
    return s, nil
}
```

Do not introduce an options abstraction solely to avoid changing unexported call sites.

## Explicit lifecycle and boundaries

- Prefer explicit construction and wiring over mutable globals or side-effectful `init` functions when initialization can fail, depends on environment, or needs test substitution.
- Make ownership of files, bodies, rows, goroutines, queues, and servers visible. Acquire and release at the same lifecycle level where possible.
- Put time and capacity limits at boundaries that own the policy. A timeout in every layer can accidentally consume or contradict one shared budget.
- Retry only operations whose semantics make retry safe, within a bounded attempt/time policy, with cancellation and backoff. Do not retry permanent validation failures or duplicate a higher layer's retry loop.
- Design idempotency explicitly when repeating a side effect can create duplicates.

For close behavior, graceful shutdown, and cleanup, read [resource management](references/resource-management.md).

## Data flow

Use streaming or iterators when materializing the full dataset creates a demonstrated memory or latency problem and the downstream protocol supports partial progress. Define error timing, cancellation, ordering, and ownership before changing a slice-returning API. See [data handling](references/data-handling.md).

## Architecture

Keep a flat or package-oriented design until independent domain rules, adapters, deployment boundaries, or team ownership make stronger separation valuable. When a formal architecture is warranted, choose it from dependency direction and change boundaries—not repository size or trend. Read [architecture choices](references/architecture.md).

Interfaces usually belong near the consumer and should contain only the behavior that consumer requires. Do not create an interface only to mock a concrete type; a small fakeable boundary may emerge from the actual caller.

## Verification

Verify observable contracts: defaults, invalid configuration, lifecycle closure, timeout and cancellation, retry safety, partial results, and compatibility. Explain why the selected pattern is simpler for the current pressure than direct code, and note any intentionally deferred complexity.

