golang-patterns
Skill1 starsChanged 58 days agoMITView on GitHub
Idiomatic Go for production services and the test suite that proves them, covering zero values, interface design, error wrapping, context and cancellation, dependency injection, allocation discipline, golangci-lint v2, table-driven tests, hand-written fakes, benchmarks, and fuzzing. Use when writing a new Go package, reviewing Go code, fixing a goroutine leak, designing an interface at the consumer, setting up Go linting, converting copy-pasted tests into a table, testing an HTTP handler, or benchmarking a hot path. Not for the language-neutral SOLID, DRY, and naming floor, use `coding-standards`.
26 other projects use a version of this.
Adopted by
Most recently taken up by
- imMamdouhaboammar/tiktok-growth-automation-meshtheir own version, first seen Oct 1, 2026
- templetongroup/radianttheir own version, first seen Sep 17, 2026
- jdanigo/hydraiatheir own version, first seen Sep 12, 2026
- bjornjee/skillstheir own version, first seen Sep 8, 2026
- jmrplens/libgen-mcptheir own version, first seen Aug 21, 2026
- SamuelNDCE/claude-super-skill-librarytheir own version, first seen Aug 1, 2026
Used with
Projects with it also use kotlin-testing, ralphinho-rfc-pipeline and 9 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
tpavanipradeepSkillkotlin-testing
Kotlin testing patterns with Kotest, MockK, coroutine testing, property-based testing, and Kover coverage. Follows TDD methodology with idiomatic Kotlin practices.
Also in 5 projects that use this
InfopibeSkillralphinho-rfc-pipeline
RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.
Also in 8 projects that use this
saxon-ySkillconfigure-ecc
Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.
Also in 10 projects that use this
InfopibeSkillcontent-hash-cache-pattern
Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.
Also in 9 projects that use this
mryeastcodeSkillsanta-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
Also in 5 projects that use this
tpavanipradeepSkillbun-runtime
Bun as runtime, package manager, bundler, and test runner. When to choose Bun vs Node, migration notes, and Vercel support.
Also in 7 projects that use this
- +4 more from Infopibe
Other versions26 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 26
- xu-xiang/everything-claude-code-zh★ 2ksame name
- loulanyue/awesome-claude-notes★ 272same name
- tpavanipradeep/everything-claude-code★ 134same name
- templetongroup/radiant★ 113same name
- Jamkris/everything-gemini-code★ 87same name
- 1024XEngineer/bytemind★ 43same name
- codelably/harmony-claude-code★ 43same name
- jmrplens/gitlab-mcp-server★ 43same name
- jmrplens/libgen-mcp★ 19same name
- FaisalAlqarni/sp-ecc★ 9same name
16 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository59 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- agentic-engineeringSkill
- ai-regression-testingSkill
- angularSkill
- ansibleSkill
- api-designSkill
- architecture-decision-recordsSkill
- ascend-memorySkill
- ascend-web-hunterSkill
- audio-scribeSkill
- automation-inventorySkill
- backend-patternsSkill
- bashSkill
- build-dependency-managementSkill
- code-formatterSkill
- code-reviewerSkill
- coding-standardsSkill
- dart-flutter-patternsSkill
- database-migrationsSkill
- deployment-patternsSkill
- design-systemSkill
- docker-patternsSkill
- e2e-runbooksSkill
- e2e-testingSkill
- embedded-c-arduinoSkill
- frontend-designSkill
- g-code-3d-printingSkill
- github-opsSkill
- git-workflowSkill
- hexagonal-architectureSkill
- home-assistantSkill
- java-coding-standardsSkill
- jetbrains-ide-opsSkill
- jira-integrationSkill
- keycloak-patternsSkill
- kicadSkill
- markdown-writerSkill
- mongodb-patternsSkill
- nextjs-app-router-patternsSkill
- node-backend-patternsSkill
- observability-and-loggingSkill
- obsidianSkill
- performance-optimizationSkill
- postgres-patternsSkill
- powershellSkill
- project-trackingSkill
- python-patternsSkill
- pytorch-patternsSkill
- react-patternsSkill
- researchSkill
- review-duplicationSkill
- security-reviewSkill
- seoSkill
- soap-webservicesSkill
- springboot-patternsSkill
- tdd-workflowSkill
- unitySkill
- web-accessibilitySkill
The file
We split this skill into the rules it gives an agent
9 rules. 0 are common, 7 are distinctive, and 2 are very specific to this project.
0
Common
Most of the 4 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 103
When one is still genuinely needed, the prose is capped at five lines and is usually one.
- Distinctive: line 190
Write the signature, write the test, watch it fail, then implement.
- Distinctive: line 219
Run the suite the way CI runs it, from the module root, with the race detector on:
- Very specific: line 225
Test shape, t.Cleanup and t.Context, testing/synctest instead of time.Sleep, parallel subtests, benchmarks, and fuzzing are in …
- Distinctive: line 291
Every exported type has a useful zero value, or an unexported field and a constructor.
- Distinctive: line 294
Every error a caller can act on is documented, including the sentinels it can match.
- Very specific: line 295
Every returned error is wrapped with %w and a lowercase operation phrase, and none is silently dropped.
- Distinctive: line 298
Every goroutine has a defined way to stop, and dependencies arrive through a constructor.
- Distinctive: line 300
Every new behaviour has a test seen to fail, repeated cases are one table, and fakes are hand-written.
“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Development Patterns
Language-level rules for production Go and the test suite that proves it: how types are shaped, how errors travel, how goroutines are stopped, how a module is laid out, and how it is tested. Go rewards the boring version, so a reader should follow control flow top to bottom without unwinding a closure. The hub carries the rules that decide most reviews, each reference file the depth for one area.
Baseline: Go 1.25, the current stable toolchain. Confirm with go version before assuming an older release: the
examples use per-iteration loop variables, any, log/slog, and testing/synctest with no compatibility note.
When to activate
- Writing, reviewing, or refactoring a Go package, command, or service.
- Designing an interface, a constructor, or a package boundary, or chasing a goroutine leak or a data race.
- Setting up
golangci-lint,go vet, and the formatting gate. - Writing table tests, fakes, benchmarks, or fuzz targets, or raising coverage on a package.
When not to activate
- Applying the cross-language design floor of SOLID, DRY, and naming. Use
coding-standards. - Applying the language-neutral red-green-refactor loop and the test pyramid. Use
tdd-workflow. - Setting up log formats, metrics, tracing, or health endpoints. Use
observability-and-logging. - Designing the HTTP or gRPC contract the service serves. Use
api-design. - Profiling a slow path before changing it. Use
performance-optimization. - Driving a browser through a user journey. Use
e2e-testing.
Make the zero value useful, and inject what it cannot hold
A type whose zero value works needs no constructor, cannot be half-initialised, and composes into other structs for
free, while a nil map or a nil channel inside a struct panics on first use. When a field genuinely cannot have a
useful zero, give the type a constructor, keep the field unexported so it cannot be skipped, and take the dependency
as an argument. A package-level *sql.DB initialised in init() cannot be swapped in a test, cannot fail loudly at
startup, and ties every consumer of the package to one instance.
// BAD
type Counter struct {
counts map[string]int
}
var db *sql.DB
func init() {
db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
}
// GOOD
type Counter struct {
mu sync.Mutex
count int
}
func NewServer(db *sql.DB) *Server {
return &Server{db: db}
}Accept interfaces, return structs, and declare them at the consumer
An interface parameter lets a caller pass anything that fits, while an interface return hides the concrete type for no benefit and blocks the caller from reaching a method the interface does not declare. The consumer also knows what it needs: an interface declared next to the implementation grows to mirror the struct, and every consumer then depends on methods it never calls.
// BAD. Declared in package postgres, mirroring the repository struct.
type UserRepository interface {
GetUser(ctx context.Context, id string) (*User, error)
SaveUser(ctx context.Context, u *User) error
Migrate(ctx context.Context) error
}
// GOOD. Declared in package service, holding only what the service calls.
type UserStore interface {
GetUser(ctx context.Context, id string) (*User, error)
}
func ProcessData(r io.Reader) (*Result, error)Doc comments: default to none
A doc comment is usually a sign that the code failed to explain itself. Before writing one, extract the unclear block into a well-named function, rename the parameters so they carry their own meaning, and tighten the types. Do that first and most doc comments have nothing left to say, which is the outcome you want. Code that explains itself cannot go stale, a comment can.
When one is still genuinely needed, the prose is capped at five lines and is usually one. Every note you add about a parameter, the result, or an error is capped at one line and only appears when it genuinely adds something: if the note does not fit on a single line, shorten it or drop it. Four rules decide what goes in. Exported identifiers are not an automatic exception: a linter wanting a comment on every exported name is not a reason to write a sentence that adds nothing.
- Prose. One sentence, starting with the identifier name, saying what it does, then only what a caller cannot infer from the signature. Nothing more.
- Describe a parameter only when the name and the type do not already convey it, meaning units, nullability, a valid
range, or who owns it afterwards.
orderID is the order identifieris noise, delete it. - Describe the result only when it is non-obvious.
- Describe the error conditions always, every one a caller can act on, and name the sentinel errors it can match
with
errors.Is. The signature says onlyerror, so this one is genuinely contract rather than decoration.
Going past the five-line prose cap is allowed only when the contract genuinely cannot be stated in fewer lines, for example a documented state machine, an ordering requirement, or a concurrency guarantee. It is an exception you justify in review, not a budget to spend. The one-line cap on a note line has no exception at all: shorten it or delete it.
// GOOD. One sentence, then only what the signature cannot carry, one line per note.
// Reserve holds stock for an order until the payment window closes.
// holdFor is capped at 15 minutes.
// Returns ErrInsufficientStock when the warehouse cannot cover the order.
func (w *Warehouse) Reserve(orderID OrderID, holdFor time.Duration) (Reservation, error)The failing shape on the same function is Reserve reserves stock. It takes an order ID and a hold duration and
returns a reservation and an error., which restates the signature and says nothing about the failure mode.
Wrap every error with context
%w keeps the original error matchable by errors.Is and errors.As while adding the operation that failed. Naked
returns of a library error give a caller a message with no idea which call produced it. Write the wrap message as a
lowercase operation phrase with no trailing punctuation, so the chain reads as one sentence when it is finally
printed. _ on an error is a decision to continue with unknown state: handle it, wrap it, or, where nothing can be
done, assign it explicitly so the choice is visible in review. Sentinel errors, custom types, and matching are in
references/errors.md.
// BAD
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, err
}
// GOOD
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}Take a context first, and never start a goroutine you cannot stop
A context.Context is the first parameter, never a struct field, and every blocking call in the function passes it
down so a cancelled request stops work instead of finishing it for nobody. That context is also the usual way a
goroutine ends: every one needs a defined way out, whether a closed channel, a cancelled context, or a WaitGroup
the caller waits on. A goroutine blocked forever on an unbuffered send is a leak that only shows up as memory growth
in production. Worker pools, errgroup, and graceful shutdown are in
references/concurrency.md.
// BAD. Context parked on a struct, and a send nothing can cancel.
type Request struct {
ctx context.Context
}
go func() { ch <- data }()
// GOOD
func FetchUser(ctx context.Context, id string) (*User, error)
go func() {
select {
case ch <- data:
case <-ctx.Done():
}
}()Test it, and watch the test fail first
Write the signature, write the test, watch it fail, then implement. A test written after the code passes on the first
run has never demonstrated it can catch anything. A table plus t.Run is the default shape, because the report then
names the input that broke rather than a line number, and the message reads got X; want Y with the input in it.
// BAD
func TestAddPositive(t *testing.T) { ... }
func TestAddNegative(t *testing.T) { ... }
// GOOD
for _, tt := range []struct {
name string
a, b int
want int
}{{"positive", 2, 3, 5}, {"mixed signs", -1, 1, 0}} {
t.Run(tt.name, func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
})
}Fake a dependency with a hand-written struct satisfying the interface the consumer declared, never with a mock framework that matches method names by string. Fake only what you cannot run: a payment API is fair, the database is not when a container or an in-memory engine exercises the real query.
Cover around 90 percent of the real logic, 100 percent on critical business logic, and exclude only generated output such as protobuf stubs. A failing coverage gate is a signal to add the missing test, never to lower the threshold. Run the suite the way CI runs it, from the module root, with the race detector on:
go test -race -coverprofile=coverage.out ./...Test shape, t.Cleanup and t.Context, testing/synctest instead of time.Sleep, parallel subtests, benchmarks,
and fuzzing are in references/testing.md.
Startup readiness log
The banner, the section order, the 2-second probe timeout, and the <url> [Connected|Warning|FAILED] result format
are one convention shared by every language, owned by observability-and-logging. What is Go-specific is where it is
emitted, after net.Listen returns and before srv.Serve(listener) blocks, so the port is already bound when the
banner says so, and that it goes through one log/slog call with a leading newline, because slog stamps a timestamp and
level per call and per-line emission would shred the banner, so the whole block is one logger.Info of the built
string. Probe with http.Client{Timeout: 2 * time.Second} so an unreachable dependency cannot stall startup, log the
detail at debug with slog.Debug, and surface only the result in the banner.
logger.Info("\n" + buildStartupLog())Avoid the classic traps
| Trap | Do instead |
Naked return in a long function | Name the returned values at the return statement |
if err == nil { ... } else { ... } | Return early on the error and leave the happy path unindented |
var results []T then append in a loop | make([]T, 0, len(items)), and strings.Builder for strings |
panic for an expected failure | Return an error and let the caller decide |
context.Context stored in a struct | Pass it as the first parameter |
| Mixing value and pointer receivers on one type | Pick one and use it for every method |
interface{} in a new signature | any, or a concrete type or type parameter |
time.Sleep to wait for a goroutine | A channel, a WaitGroup, or a context deadline |
time.Sleep to wait in a test | testing/synctest, or a channel the test blocks on |
Reference files
| Open this | For |
| references/errors.md | Sentinels, custom error types, errors.Is/As, joining, panics |
| references/concurrency.md | Worker pools, errgroup, channels, shutdown, sync.Pool |
| references/project-layout.md | Module layout, package naming, options pattern, embedding |
| references/tooling.md | Build and test commands, golangci-lint v2 configuration, CI |
| references/testing.md | Test shape, t.Cleanup, synctest, parallel subtests, coverage |
| references/table-tests.md | Table shapes, error cases, subtests, golden files, comparison |
| references/mocks-and-fakes.md | Fakes, stubs, spies, interfaces at the consumer, httptest |
| references/integration.md | Real databases, containers, build tags, HTTP handler tests |
| references/benchmarks.md | Benchmarks, allocation counts, profiles, fuzzing, coverage |
Related skills
coding-standardsfor the cross-language floor this skill sits on.tdd-workflowfor the language-neutral red-green-refactor loop and the test pyramid.observability-and-loggingfor slog discipline, metrics, and the startup readiness log.api-designfor the shape of the HTTP or gRPC contract a Go service serves.performance-optimizationfor what to do with a benchmark once you have one.docker-patternsfor building and shipping the resulting binary.
Checklist
- Every exported type has a useful zero value, or an unexported field and a constructor.
- Functions accept interfaces and return concrete types, and interfaces are declared at the consumer.
- Doc comments are absent, or one sentence plus only the notes the signature cannot carry.
- Every error a caller can act on is documented, including the sentinels it can match.
- Every returned error is wrapped with
%wand a lowercase operation phrase, and none is silently dropped. An explicit_ =assignment appears only where nothing can be done. context.Contextis the first parameter everywhere and is passed to every blocking call.- Every goroutine has a defined way to stop, and dependencies arrive through a constructor.
- Slices are preallocated where the length is known and strings are built with a
Builder. - Every new behaviour has a test seen to fail, repeated cases are one table, and fakes are hand-written.
gofmt,go vet,golangci-lint run, andgo test -race ./...all pass, with around 90 percent coverage.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

