Go Design Patterns

VerifiedSafe

Idiomatic Go patterns for production code: functional options, error flow, lifecycle, resilience. Apply when selecting architectural patterns or implementing Go idioms.

Sby Skills Guide Bot
DevelopmentIntermediate
8/29/2026
Claude CodeCodex
#go#design-patterns#api-design#resource-management#architecture

Recommended for

Automated summary

A guide to Go design patterns and idioms for picking the smallest abstraction that fits: functional options, constructors, error flow, resource lifecycle, graceful shutdown and resilience.

Strengths

  • Offers a checklist of concrete, checkable rules (functional options, avoid init(), mandatory timeouts, bounded resources)
  • Clearly separates a design mode from a review mode with targeted audit instructions
  • Favors simplicity and explicitly pushes back on premature abstraction
  • Covers real production concerns: graceful shutdown, context-aware retries, streaming and //go:embed

Limitations

  • Defers to sibling skills in the same collection (error handling, context, code style) instead of covering them in depth
  • Assumes solid prior Go experience; some idioms may be opaque to newcomers
  • Provides principles and pointers rather than complete code examples
When to use it

Reach for it when designing a Go API or package, weighing architectural patterns, or auditing existing code for lifecycle and resilience issues.

When not to use it

Skip it for narrow Go chores such as fixing a typo, reformatting a file, or writing a single unit test with no design implications.

Security analysis

Safe
Quality score88/100

The skill is a prose/guidance document about idiomatic Go design patterns. Its declared tools (Read/Edit/Write/Glob/Grep plus scoped Bash for go, golangci-lint, and git, and Agent) are all legitimate for a Go coding/refactoring assistant, and the Bash grants are command-prefixed rather than unrestricted. There are no curl|sh pipelines, no rm -rf, no base64-obfuscated payloads, no attempts to read or exfiltrate secrets/SSH keys/tokens, and no instructions to disable safety or push to remote destinations. Content is purely educational code examples.

No concerns found

How this analysis is made

Examples

Design an options API
I'm building a new Go HTTP client package. Should I use functional options or a config struct? Show me the idiomatic constructor with validation.
Add graceful shutdown
Review this Go service's main() and add graceful shutdown with context cancellation for the HTTP server and worker pool.
Audit for design smells
Scan this package for init() abuse, unbounded queues, missing timeouts and implicit global state, and report the findings before refactoring.

name: golang-design-patterns description: "Idiomatic Golang design patterns β€” functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, streaming, and more. Apply when explicitly choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem." user-invocable: true license: MIT compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang. metadata: author: samber version: "1.2.0" openclaw: emoji: "πŸ—" homepage: https://github.com/samber/cc-skills-golang requires: bins: - go install: [] allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent AskUserQuestion paths:

  • "**/*.go"

Persona: You are a Go architect who values simplicity and explicitness. You apply patterns only when they solve a real problem β€” not to demonstrate sophistication β€” and you push back on premature abstraction.

Modes:

  • Design mode β€” creating new APIs, packages, or application structure: ask the developer about their architecture preference before proposing patterns; favor the smallest pattern that satisfies the requirement.
  • Review mode β€” auditing existing code for design issues: scan for init() abuse, unbounded resources, missing timeouts, and implicit global state; report findings before suggesting refactors.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-design-patterns skill takes precedence.

Go Design Patterns & Idioms

Idiomatic Go patterns for production-ready code. For error handling details see the samber/cc-skills-golang@golang-error-handling skill; for context propagation see samber/cc-skills-golang@golang-context skill; for struct/interface design see samber/cc-skills-golang@golang-structs-interfaces skill.

Best Practices Summary

  1. Constructors SHOULD use functional options β€” they scale better 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 at runtime
  3. Avoid init() β€” runs implicitly, cannot return errors, makes testing unpredictable. Use explicit constructors
  4. Enums SHOULD start at 1 (or Unknown sentinel at 0) β€” Go's zero value silently passes as the first enum member
  5. Error cases MUST be handled first with early return β€” keep happy path flat
  6. Panic is for bugs, not expected errors β€” callers can handle returned errors; panics crash the process
  7. defer Close() immediately after opening β€” later code changes can accidentally skip cleanup
  8. runtime.AddCleanup over runtime.SetFinalizer β€” finalizers are unpredictable and can resurrect objects
  9. Every external call SHOULD have a timeout β€” a slow upstream hangs your goroutine indefinitely
  10. Limit everything (pool sizes, queue depths, buffers) β€” unbounded resources grow until they 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; stream keeps memory constant
  16. //go:embed for static assets β€” embeds at compile time, eliminates 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) and allocates
  19. Compile-time interface checks: var _ Interface = (*Type)(nil)
  20. A little recode > a big dependency β€” each dep adds attack surface and maintenance burden
  21. Design for testability β€” accept interfaces, inject dependencies

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),
)

Constructors SHOULD use functional options β€” they scale better with API evolution and require less code. Use builder pattern only if you need complex validation between configuration steps.

Constructors & Initialization

Avoid init() and Mutable Globals

init() runs implicitly, makes testing harder, and 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

Zero values should represent invalid/unset state:

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

Compile-Time Interface Checks

β†’ See samber/cc-skills-golang@golang-structs-interfaces for the var _ Interface = (*Type)(nil) pattern.

Error Flow Patterns

Error cases MUST be handled first with early return β€” keep the happy path at minimal indentation. β†’ See samber/cc-skills-golang@golang-code-style for the full pattern and examples.

When to Panic vs Return Error

  • Return error: network failures, file not found, invalid input β€” anything a caller can handle
  • Panic: nil pointer in a place that should be impossible, violated invariant, Must* constructors used at init time
  • .Close() / Flush() errors: read-only cleanup can often use defer f.Close(), but 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 one allocates. Stay in one type until you need the other.

Iterators & Streaming for Large Data

Use iterators (Go 1.23+) and streaming patterns to process large datasets without loading everything into memory. For large transfers between services (e.g., 1M rows DB to HTTP), stream to prevent OOM.

For code examples, see Data Handling Patterns.

Resource Management

defer Close() immediately after opening β€” don't wait, don't forget:

f, err := os.Open(path)
if err != nil {
    return err
}
defer f.Close() // right here, not 50 lines later

rows, err := db.QueryContext(ctx, query)
if err != nil {
    return err
}
defer rows.Close()

For 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 the developer which architecture they prefer: clean architecture, hexagonal, DDD, or flat layout. Don't impose complex architecture on a small project.

Core principles regardless of architecture:

  • Keep domain pure β€” no framework dependencies in the 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 |

Code Philosophy

  • Avoid repetitive code β€” but don't abstract prematurely
  • Minimize dependencies β€” a little recode > a big dependency
  • Design for testability β€” accept interfaces, inject dependencies, keep functions pure

Cross-References

  • β†’ See samber/cc-skills-golang@golang-data-structures skill for data structure selection, internals, and container/ packages
  • β†’ See samber/cc-skills-golang@golang-error-handling skill for error wrapping, sentinel errors, and the 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 for safely staging a migration toward one of these patterns (options struct, DI, consumer-side interfaces) across an existing codebase

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/go-design-patterns-mte1lira/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/go-design-patterns-mte1lira' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/go-design-patterns-mte1lira/download' --output '.skill-downloads/go-design-patterns-mte1lira/SKILL.md.part' && mv '.skill-downloads/go-design-patterns-mte1lira/SKILL.md.part' '.skill-downloads/go-design-patterns-mte1lira/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Environment declared by the author: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Tools declared by the author (check availability in your agent): Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/go-design-patterns-mte1lira/SKILL.md' && test -s '.skill-downloads/go-design-patterns-mte1lira/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/golang-design-patterns' && cp -R '.skill-downloads/go-design-patterns-mte1lira' '.claude/skills/golang-design-patterns'

Codex
test -f '.skill-downloads/go-design-patterns-mte1lira/SKILL.md' && test -s '.skill-downloads/go-design-patterns-mte1lira/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/golang-design-patterns' && cp -R '.skill-downloads/go-design-patterns-mte1lira' '.agents/skills/golang-design-patterns'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js β‰₯ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/go-design-patterns-mte1lira'

openskills read 'go-design-patterns-mte1lira'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/go-design-patterns-mte1lira/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills