golang-design-patterns
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 architec
Supply asset profile
Coding and developer agents
Code review, repo analysis, testing, CI, GitHub, DevOps, and developer workflow skills.
Scenario
GitHub automation
I need my agent to triage GitHub issues, review pull requests, and summarize repository changes.
Agent fit
Claude Code + OpenAI Agents + CLI
Codex, Claude Code, Cursor, CLI, or custom agents.
Install
Ready
npx skills add samber/cc-skills-golang --skill golang-design-patterns
Maintenance
fresh
1d since push
Risk
Needs review
Dependency or permission surface needs review
GitHub quality
3.0K
82/100 Quality · 78/100 Trust
Coverage tags
Review notes
Dependency or permission surface needs review · Permission surface may require sandboxing
Agent adoption scorecard
Trust, audit, and install readiness at a glance
These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.
Quality
StrongSolid option that is likely worth shortlisting for production workflows.
Trust
Sandbox onlyUseful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
Audit
Needs reviewA machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
OpenAgentSkill Trust Score v5
Human review before install
Run only in a sandbox and compare close alternatives before using it for real work.
Stars
3.0K GitHub stars
Repo activity
3.0K stars, 197 forks
Maintenance
1d since push
License
MIT
Install
npx skills add samber/cc-skills-golang --skill golang-design-patterns
Install safety
standard package or runtime install path
Permission surface
shell or command execution, filesystem or document access
Agent outcomes
No agent outcome data yet
Docs
Strong README/SKILL.md context
Risk summary
Review before production
- Financial research output is not financial advice; require human review before any live investment decision.
- Quality score needs review
- Permission surface needs review: shell or command execution, filesystem or document access
- Dependency/runtime risk: command execution surface, external package install surface
Install readiness
Install path available
- Install path is available
- Repository evidence is available
- License is declared
- No Agent Proven outcome evidence yet
Agent-readable metadata
Machine-readable decision data for this skill.
Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.
Suited tasks
- GitHub automation workflows
- Claude Code teams
- teams that value GitHub adoption signals
- Inspect repository metadata
Suited agents
Install decision
- Command
- npx skills add samber/cc-skills-golang --skill golang-design-patterns
- Policy
- review
- Human review
- yes
Trust and risk
- Trust
- 70/100
- Audit
- 84/100
- Risk level
- Needs review
Outcome loop
- Endpoint
- /api/agent/outcome
- Event ID
- resolve
- Outcomes
- 5
Install command
npx skills add samber/cc-skills-golang --skill golang-design-patternsDo not use when
- teams that need a vendor-supported SLA
- high-compliance environments without internal security review
- No major risk signals from current metadata
- High-risk permission hints: Shell or command execution
- Dependency or permission surface needs review
Alternative
Last30days Skill
53.5K Stars
npx skills add mvanhorn/last30days-skill -g
Alternative
Academic Research Skills
38.4K Stars
npx skills add Imbad0202/academic-research-skills
Alternative
GPT Researcher
28.0K Stars
npx skills add assafelovic/gpt-researcher
Alternative
DeepResearch
19.8K Stars
npx skills add Alibaba-NLP/DeepResearch
Agent safety v2
52/100 · Avoid automatic install
Sparse or mixed signals. Useful for discovery, but not for autonomous installation.
Test manually in an isolated workspace and compare against safer alternatives.
high
Shell or command execution
Skill metadata references terminal, CLI, shell, subprocess, or command execution workflows.
medium
Network access
Skill likely fetches remote pages, APIs, repositories, or external services.
medium
Filesystem access
Skill may read or write project files, documents, generated artifacts, or local workspace state.
medium
Database access
Skill may inspect schemas, query databases, or work with persistent stores.
- High-risk permission hints: Shell or command execution
- Dependency or permission surface needs review
Install targets
Install this skill in your agent workflow
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
OpenAgentSkill CLI
Resolve policy, run the source installer safely, and report a verified install receipt.
$ npx --yes https://github.com/Leon-Drq/openagentskill/releases/download/cli-v0.2.1/openagentskill-0.2.1.tgz install samber-golang-design-patternsAgent resolve plan
Let an agent verify fit before installing.
The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.
Open JSON
/api/agent/resolve?task=Use%20golang-design-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Resolve text
/api/agent/resolve?task=Use%20golang-design-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium&format=text
Install handoff
/api/skills/samber-golang-design-patterns/install
Agent should check
- Task fit and alternatives from Resolve API.
- Audit score, trust score, and safety policy warnings.
- Install target compatibility for Codex, Claude Code, Cursor, or CLI.
Copy prompt
Task: Use golang-design-patterns in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20golang-design-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/samber-golang-design-patterns/install
Install command: npx skills add samber/cc-skills-golang --skill golang-design-patterns
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.Agent handoff
Give an agent the install path, not another directory page.
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
Install handoff
/api/skills/samber-golang-design-patterns/install
LLM text format
/api/skills/samber-golang-design-patterns/install?format=text
Find alternatives
/api/skills/search?q=golang-design-patterns&limit=3
Agent prompt
Use golang-design-patterns for this task. Review https://www.openagentskill.com/api/skills/samber-golang-design-patterns/install, then install with: npx skills add samber/cc-skills-golang --skill golang-design-patternsRegistry metadata
Agent-readable profile for automatic skill selection.
This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.
Manifest
/api/registry/manifest/samber-golang-design-patterns
LLM text
/api/registry/manifest/samber-golang-design-patterns?format=text
Install alias
/api/registry/install/samber-golang-design-patterns
Recommend
/api/registry/recommend?task=Use%20golang-design-patterns%20in%20an%20agent%20workflow&limit=3
Agent fit
GitHub automation
Use-case tags
Platforms
Claude Code, OpenAI Agents
Audit report
Needs review · 84/100
A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
Agent decision cockpit
Primary pick for GitHub automation
Use this as a leading candidate, then validate the README and install path in your own agent stack.
Role in stack
Primary pick
Primary fit
GitHub automation
Trust label
Production-ready
Install path
Command ready
Use when
- GitHub automation workflows
- Claude Code teams
- teams that value GitHub adoption signals
Evidence
- 3,022 GitHub stars
- recent repository activity
- install command or GitHub repo available
- 82/100 quality profile
- 4 OpenAgentSkill engagement events
review first
- No major risk signals from current metadata
Implementation path
- 1Install it in a sandbox agent and run one GitHub automation task end to end.
- 2Compare output quality, latency, and failure behavior against at least one alternative.
- 3Promote it into production only after reviewing repository permissions, license, and maintenance signals.
Trust profile
Sandbox only
Useful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
GitHub adoption
PASS3.0K GitHub stars
Stars/forks activity
INFO3.0K stars, 197 forks; issue activity unavailable in current metadata
Recent maintenance
PASS1d since push
License clarity
PASSMIT
Good signals
- AI review approved
- Install path is available
- Repository evidence is available
- Recently maintained repository
- Meaningful GitHub adoption signal
- Install command has no obvious high-risk pattern
- Outcome loop is ready but needs first real agent run
Review before install
- Financial research output is not financial advice; require human review before any live investment decision.
- Quality score needs review
- Permission surface needs review: shell or command execution, filesystem or document access
- Dependency/runtime risk: command execution surface, external package install surface
- Permission surface: shell or command execution, filesystem or document access
- No real agent outcome reports yet
- Human review required before unattended installation
Recommended action
Run only in a sandbox and compare close alternatives before using it for real work.
Quality profile
Strong candidate for agent workflows
Solid option that is likely worth shortlisting for production workflows.
Workflow fit
Use this skill in these scenarios
Manage repositories
GitHub automation
I need my agent to triage GitHub issues, review pull requests, and summarize repository changes.
Build and ship code
Coding agents
I need a coding agent that can understand a repository, edit code, and review pull requests.
Investigate faster
Research agents
I need my agent to research a topic, compare sources, and produce a concise report.
Workflow fit
Add it to a complete workflow
Inspect, patch, and verify code
Coding review agent
A workflow for software agents that inspect repositories, review pull requests, generate tests, and turn findings into shippable patches.
Find, compare, and synthesize
Research report agent
A workflow for agents that gather sources, compare claims, summarize long material, and draft useful research briefs.
Ingest, retrieve, and cite
RAG knowledge base
A workflow for document-heavy agents that ingest files, create searchable knowledge, retrieve relevant context, and answer with grounded sources.
Alternative shortlist
Compare before you install
Similar skills that may fit this task.
Last30days Skill
Research the last 30 days across Reddit, X, YouTube, Hacker News, Polymarket, GitHub, and the web, then synthesize a grounded brief for an AI agent.
Academic Research Skills
Academic Research Skills for Claude Code: research → write → review → revise → finalize
GPT Researcher
Run autonomous deep research over web and local sources
DeepResearch
Tongyi Deep Research, the Leading Open-source Deep Research Agent
Overview
--- 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)
```go 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
```go // 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:
```go type Status int
const ( StatusUnknown Status = iota // 0 = invalid/unset StatusActive // 1 StatusInactive // 2 StatusSuspended // 3 ) ```
### Compile Regexp Once
```go // 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
```go 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](references/data-handling.md).
## Resource Management
`defer Close()` immediately after opening — don't wait, don't forget:
```go 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](references/resource-management.md).
## Resilience & Limits
### Timeout Every External Call
```go 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](references/architecture.md) | High-level principles, when each architecture fits | | [Clean Architecture](references/clean-architecture.md) | Use cases, dependency rule, layered adapters | | [Hexagonal Architecture](references/hexagonal-architecture.md) | Ports and adapters, domain core isolation | | [Domain-Driven Design](references/ddd.md) | 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
Technical details
- Version
- 1.0.0
- License
- MIT
- Last updated
- Aug 21, 2026
- Published
- Aug 21, 2026
Decision snapshot
Primary pick
3,022 GitHub stars
Audit
Install review
Install and adoption review
- Security
- 78/100
- Maintenance
- 100/100
- Install
- 92/100
Agent-proven evidence
Agent-proven evidence
Outcome reports after resolve, review, install, and one narrow run.
- Success rate
- —
- Recent failure
- —
- Outcomes
- 0
- Output quality
- —
- Failed
- 0
- Not relevant
- 0
- Installs
- 0
- Risk blocked
- 0
- Setup needed
- 0
- Production
- 0
No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.
Install
Add to agent workflow
Free and open source. Review the report before installing into production agents.
Growth loop
Share kit
Scenario-led draft for golang-design-patterns, ready for a manual X post.
golang-design-patterns: Idiomatic Golang design patterns — functional options, constructors, error flow and cascading... 3.0K stars https://www.openagentskill.com/skills/samber-golang-design-patterns?ref=x
Optional reply with install command
Listing + install path for golang-design-patterns: https://www.openagentskill.com/skills/samber-golang-design-patterns?ref=x Install: npx skills add samber/cc-skills-golang --skill golang-design-patterns
Listing source
Registry indexed
This listing was indexed from public sources and is not marked official until a maintainer claim is approved.
- Creator
- samber
- Source
- samber/cc-skills-golang
- Indexed by
- OpenAgentSkill community index
Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.
Claim this skillOwner claim
Claim this skill listing
This Registry indexed listing is attributed to samber but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.
Creator backlink kit
Add the evidence badges to your README
Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.
[](https://www.openagentskill.com/skills/samber-golang-design-patterns)
[](https://www.openagentskill.com/skills/samber-golang-design-patterns)
[](https://www.openagentskill.com/skills/samber-golang-design-patterns/audit)
[](https://www.openagentskill.com/skills/samber-golang-design-patterns)Author
samber
@samber
Tags
Platform fit
Health signals
- GitHub stars
- 3.0K
- Quality score
- 48/100
- Last GitHub push
- Aug 21, 2026
- Framework hints
- Unknown
- OpenAgentSkill views
- 4
- Install copies
- 0
- Outbound clicks
- 0
Community signal
Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.
Trust & safety
Sandbox only
- GitHub adoption3.0K GitHub starsPASS
- Stars/forks activity3.0K stars, 197 forks; issue activity unavailable in current metadataINFO
- Recent maintenance1d since pushPASS
- License clarityMITPASS
- README/SKILL.md completenessMetadata includes enough usage and workflow contextPASS
- Dependency/runtime riskcommand execution surface, external package install surfaceCHECK
Related skills
Last30days Skill
Research the last 30 days across Reddit, X, YouTube, Hacker News, Polymarket, GitHub, and the web, then synthesize a grounded brief for an AI agent.
53.5K StarsAcademic Research Skills
Academic Research Skills for Claude Code: research → write → review → revise → finalize
38.4K StarsGPT Researcher
Run autonomous deep research over web and local sources
28.0K StarsDeepResearch
Tongyi Deep Research, the Leading Open-source Deep Research Agent
19.8K Stars