anantbhandarkar/make-it-right/mir-backend-go
Claude Code and agent skill by anantbhandarkar/make-it-right
- community
Checking that the SKILL.md file is still in the repository.
Make It Right (Go runtime tier). Go 1.25/1.26 runtime reliability footguns shared across every Go backend framework (Gin, Fiber, Echo, chi, stdlib net/http) — distinct from the generic backend gates and from any one framework's mechanics. Covers: goroutine leaks (the #1 Go reliability bug) and the runtime goroutineleak profile, context propagation and cancellation, data races and `go test -race`, channel ownership rules, goroutine-level panic recovery, the nil-interface/nil-pointer trap, defer-in-loop resource buildup, slice aliasing, error wrapping with errors.Is/As/AsType, sync.WaitGroup.Go, the Go 1.22 per-iteration loop-variable change and its go.mod gating, deterministic concurrency tests with testing/synctest, container-aware GOMAXPROCS, log/slog structured logging, and Go-level security mechanics (http.Server timeouts, net/http CrossOriginProtection, os.Root path containment, SSRF dialer control, module checksum verification, govulncheck). TRIGGER when the backend runtime is Go — sits between mir-backend (generic gates) and the framework module. SKIP for Python/Node/JVM/Rust/.NET/Ruby/PHP/BEAM runtimes (each has its own mir-backend-<runtime> tier), and for framework-library mechanics: Gin's c.Copy() and SetTrustedProxies go to mir-backend-go-gin, Fiber's pooled Ctx and fasthttp constraints to mir-backend-go-fiber, Echo's Bind/Validate and IPExtractor to mir-backend-go-echo.
Install
npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-goSKILL.md
The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-go.
/mir-backend-go · Make It Right (Go runtime)
The middle tier. mir-backend decides what is correct (any language). The framework module (e.g. mir-backend-go-gin) knows the library's mechanics. This tier owns what is true for all Go backends because they run on the Go runtime — the goroutine scheduler, memory model, and process model that Gin, Fiber, Echo, chi, and raw net/http all inherit.
Runtime state, verified 13 Aug 2026. Load order: mir-backend → mir-backend-go → <framework module>.
| Release | Status | Notes | |
|---|---|---|---|
| Go 1.26 (1.26.5, 2026-07-07) | current stable | Green Tea GC on by default; goroutineleak profile behind GOEXPERIMENT=goroutineleakprofile; errors.AsType; slog.NewMultiHandler | |
| Go 1.25 (1.25.12, 2026-07-07) | supported | sync.WaitGroup.Go; testing/synctest stable; container-aware GOMAXPROCS; net/http.CrossOriginProtection | |
| Go 1.24 and older | end of life | No security patches. Go supports each major only until two newer majors exist | |
| Go 1.27 | RC2 as of 2026-07-07, expected Aug 2026 | Final release not confirmed at time of writing — verify before relying on it |
Set the floor at Go 1.25. Anything below it is an unpatched toolchain. Note the two version knobs are different things: the toolchain you build with decides which security fixes you have; the go line in go.mod decides which language and GODEBUG defaults apply (see footgun 11).
The Go footguns AI walks into (framework-agnostic)
1. Goroutine leaks — the #1 Go reliability bug
A goroutine blocked forever on a channel send or receive with no exit path leaks memory and any handles (DB connections, file descriptors) it holds. The runtime never garbage-collects a blocked goroutine. Under load, hundreds of leaked goroutines exhaust memory silently.
- Always give every goroutine a way to exit. The standard mechanism: accept a
context.Contextas the first argument andselectonctx.Done()alongside the blocking operation. - Leak pattern — no exit:
``go // WRONG: goroutine blocked forever if nobody reads ch go func() { ch <- result }() ``
- Fixed — context exit:
``go go func() { select { case ch <- result: case <-ctx.Done(): } }() ``
- Long-running worker loops must
selectonctx.Done()in every iteration. - Two detection tools, use both.
uber-go/goleakin tests fails a package when goroutines outlive it. The runtime's owngoroutineleakprofile finds leaks in a running process: it reports goroutines blocked on a concurrency primitive that is unreachable from any runnable goroutine, so it cannot become unblocked. Enable it on Go 1.26 withGOEXPERIMENT=goroutineleakprofileat build time and read/debug/pprof/goroutineleak. It is a regular profile in Go 1.27 (unreleased at time of writing). - The profile misses leaks where the channel is still reachable through a global or through a live goroutine's locals. Keep
goleakin tests; do not treat a clean profile as proof.
2. Context propagation and cancellation
context.Context is the Go runtime's cancellation, deadline, and value bus. Failing to propagate it means cancellation and timeouts are silently ignored — requests pile up even after the client disconnects.
- Pass `ctx` as the first argument through the entire call chain — every function that does I/O, calls an external service, or blocks must accept and forward the context.
- Honor `ctx.Done()` on every blocking operation: DB queries, HTTP calls, gRPC calls, queue publishes.
- Derive per-operation timeouts with `context.WithTimeout`; this bounds downstream latency and prevents cascading stalls:
``go ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // always call cancel to release resources row, err := db.QueryRowContext(ctx, query, args...) ``
- Use
context.WithTimeoutCause/context.WithCancelCausewhen you need to tell "client hung up" apart from "we hit our own deadline" in logs —context.Cause(ctx)returns the specific error,ctx.Err()only ever returnsDeadlineExceededorCanceled. - Never store a context in a struct field for later use — pass it at call time. Stored contexts outlive their validity.
context.Background()is only for top-level entry points (main, test setup). Everywhere else, derive from the incoming ctx.- Work that must outlive the request needs a detached context —
context.WithoutCancel(ctx)keeps the values (trace IDs, tenant) while dropping the cancellation. Apply your own timeout after detaching, because the derived context now has none. Detaching only survives the handler, not the process: if losing the work is unacceptable (payment capture, outbound email, webhook delivery), it belongs in a durable queue or transactional outbox, not a goroutine — the next deploy kills it after you already returned 202.
3. Data races on shared maps, slices, and structs
Go's runtime panics on a concurrent map write (fatal error: concurrent map read and map write). Races on other types produce silent data corruption that surfaces intermittently in production but may be invisible in tests.
- Any state read or written from more than one goroutine must be protected with
sync.Mutex,sync.RWMutex,sync/atomic, or a dedicated owner goroutine (the channel-passing pattern). - Never pass a
mapor[]Tto a goroutine and also read/write it from the caller without synchronization. - Test every concurrent package with `go test -race`. The race detector catches most write-write and write-read races with very low false-positive rate. Add it to CI:
`` go test -race ./... ``
- The detector only reports races it actually observes. A single-shot test rarely interleaves — run contended tests with
-race -count=10or drive them withtesting/synctest(footgun 12). sync.Mapis appropriate only when writes are rare and reads dominate, or when keys are disjoint across goroutines. For general use, a mutex-guarded map is clearer. Prefer the typedatomic.Int64/atomic.Pointer[T]types over the oldatomic.AddInt64(&x, 1)function calls — the typed values cannot be read non-atomically by mistake.
4. Channel ownership and closing rules
Misusing channels is the second most common source of Go panics after nil dereferences.
- Only the sender closes a channel. A receiver must never close. Closing from two goroutines panics.
- Sending on a closed channel panics — never close a channel that another goroutine may still send to.
- `range` over a channel reads until the channel is closed — if you intend to drain a channel with
range, the sender must close it when done; otherwise the loop hangs. - Unbuffered send with no receiver blocks the sender goroutine forever — see footgun 1. Use buffered channels when the producer must not block, but beware that a full buffer just defers the block.
- Prefer
close(done)as a broadcast signal to multiple goroutines over sending N values.
5. Panic in a goroutine crashes the whole process
An unrecovered panic in any goroutine terminates the process — unlike exceptions in most runtimes, there is no per-goroutine catch-all. This means a single malformed request can bring down the server.
- `recover()` only works in the same goroutine and only in a deferred function. A top-level
recoverinmaindoes not catch panics in spawned goroutines. - Every goroutine that handles per-request or per-task work must have its own
recover:
``go go func() { defer func() { if r := recover(); r != nil { slog.Error("recovered panic", "panic", r, "stack", string(debug.Stack())) } }() doWork(ctx) }() ``
- Web frameworks (Gin
Recovery(), Echomiddleware.Recover(), Fiberrecover.New()) install this at the HTTP layer — but goroutines you spawn inside a handler are not covered by the framework middleware and need their own recover. sync.WaitGroup.Godoes not recover. A panic inside it still kills the process; it only guaranteesDoneis called on the way out.
6. Nil interface vs. nil pointer — the typed-nil trap
The most common source of surprising if err != nil failures in Go. An interface value is nil only when both its type and value are nil. A non-nil interface holding a nil pointer is non-nil.
- A function whose declared return type is
errormust return barenil, never a nil-valued concrete pointer. Same trap for a struct field or a channel of interface type. - When checking:
errors.Is/errors.Asare safe.== nilon an interface is the trap.
7. defer inside a loop — resource buildup until function return
defer statements execute when the enclosing function returns, not when the block or loop iteration exits. Deferring rows.Close() or f.Close() inside a loop keeps every handle open until the whole function returns.
The same shape applies to rows.Close(), mu.Unlock(), and tx.Rollback() in a loop. On a long input list this is a file-descriptor or connection-pool exhaustion, not a leak you notice in tests.
8. Slice aliasing and backing-array mutation
Slices in Go are a view over a backing array. append may or may not allocate a new array depending on capacity, and sub-slices share the same backing memory. Passing a slice to a goroutine while still appending to it in the caller is a data race (see footgun 3) and causes silent corruption.
- If you need an independent copy, use
slices.Clone(src)(ormake+copyfor pre-Go-1.21 code). - When passing a slice to a goroutine, either pass a copy, or ensure the goroutine only reads after the caller is done writing.
append(s, x)may silently reuse capacity from a parent slice; if a parent slice was sliced then appended to, the parent's backing array may be mutated. Uses[lo:hi:hi](three-index slice) to cap capacity and force an allocation on the first append.
9. Error discipline — always check, always wrap
Go has no exceptions; ignored errors are discarded results. Nothing in the compiler stops you — a call used as a statement (f.Write(b)) throws away every return value including the error. The compiler only rejects an unused local variable, which is why _ = is the idiom that silences it.
- Never discard an error with
_unless you have a documented reason. The silent_ = f.Write(...)pattern hides I/O failures. - Wrap errors with context using
fmt.Errorf("context: %w", err)so callers and logs show the full chain without losing the sentinel forerrors.Is/errors.As. - On Go 1.26+,
errors.AsType[*MyError](err)replaces the two-line declare-then-errors.Asdance and cannot be called with a non-pointer target by mistake. - Returning a bare
errfrom a deep call loses all context about where it happened — add a short annotation at each layer boundary. log.Fatal/os.Exitinside a library are forbidden — they bypassdefercleanup and callers cannot handle them. Return errors; let the entry point decide whether to exit.
10. sync.WaitGroup — use wg.Go, not Add/Done by hand
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/mir-backend-go/SKILL.md
Popularity
- Repository stars
- 15
- 7-day trend score
- 14
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-go)