| name | golang-patterns |
| description | Use when writing or refactoring Go code, designing packages, implementing concurrency, using generics, or building HTTP services. Do NOT use for database optimization (use sql-optimization-patterns), API design (use api-design), or CI/CD (use github-actions). |
| paths | **/*.go, **/go.mod, **/go.sum |
Go Development Patterns
Idiomatic Go patterns and best practices for building robust, efficient, and maintainable applications. Based on Effective Go, Go Code Review Comments, Uber Go Style Guide, and Google Go Style Guide.
Quick Start
When to Activate
- Writing new Go code
- Reviewing or refactoring Go code
- Designing Go packages/modules
- Implementing concurrency patterns
- Building HTTP services with net/http
- Writing tests, benchmarks, or fuzz tests
- Using generics or iterators
CRITICAL Rules
MUST DO
- Handle every error โ Never use
_ for errors unless explicitly justified with comment
- Wrap errors with context โ
fmt.Errorf("operation %s: %w", name, err) always
- Pass context.Context as first param โ Never store in struct fields
- Use structured concurrency โ Every goroutine must have clear ownership and shutdown path
- Close resources with defer โ
defer f.Close() immediately after successful open
- Accept interfaces, return structs โ Define interfaces at consumer, not provider
- Make zero values useful โ Design types to work without explicit initialization
- Format with gofmt/goimports โ Non-negotiable, run before every commit
- Preallocate slices โ
make([]T, 0, knownLen) when capacity is known
- Use
errors.Is/errors.As โ Never compare errors with == (except sentinel errors pre-1.13)
MUST NOT DO
panic for control flow โ Only for truly unrecoverable programmer errors
- Naked returns in long functions โ Only acceptable in very short functions (< 5 lines)
init() with side effects โ Avoid init(); prefer explicit initialization via constructors
- Global mutable state โ Use dependency injection instead of package-level vars
- Goroutine leaks โ Always provide cancellation path (context, done channel, or buffered channel)
sync.Mutex copying โ Never copy a Mutex; embed as pointer or use pointer receiver
interface{} when generics fit โ Use type parameters for type-safe collections (Go 1.18+)
- Log AND return error โ Handle errors once: either log or return, never both (Uber Guide)
math/rand for security โ Use crypto/rand for keys, tokens, and secrets
fmt.Sprintf for int-to-string โ Use strconv.Itoa/strconv.FormatInt (3x faster)
Reference Guide
Load detailed guidance based on context:
| Topic | Reference | Load When |
|---|
| Concurrency | references/concurrency-patterns.md | goroutines, channels, sync, errgroup, context, graceful shutdown |
| Modern Go (1.21-1.23+) | references/modern-go.md | slog, iterators, enhanced ServeMux, generics, range-over-int |
| Testing | references/testing-patterns.md | table-driven tests, fuzz, benchmarks, mocking, golden files, HTTP handler tests |
Decision Tree
Writing Go code?
โโ Error handling?
โ โโ Known error condition โ sentinel error (var ErrXxx = errors.New(...))
โ โโ Error needs context โ fmt.Errorf("context: %w", err)
โ โโ Multiple errors โ errors.Join (Go 1.20+)
โ โโ Rich error info needed โ custom error type implementing error interface
โโ Concurrency needed?
โ โโ Fire-and-forget task โ references/concurrency-patterns.md (Worker Pool)
โ โโ Multiple concurrent ops โ errgroup.Group
โ โโ Shared state โ sync.Mutex or channel
โ โโ Cancellation/timeout โ context.WithCancel / WithTimeout
โ โโ Graceful shutdown โ signal.Notify + context
โโ HTTP service?
โ โโ Method + path routing โ Enhanced ServeMux (references/modern-go.md)
โ โโ Middleware pattern โ func(http.Handler) http.Handler
โ โโ Structured logging โ slog (references/modern-go.md)
โโ Type-safe collection?
โ โโ Simple generic func โ references/modern-go.md (Generics)
โ โโ Iterator pattern โ iter.Seq / iter.Seq2 (Go 1.23+)
โ โโ Type constraint โ interface with ~type union
โโ Testing?
โ โโ Multiple inputs โ Table-driven tests
โ โโ Input validation โ Fuzz tests
โ โโ Performance measurement โ Benchmarks
โ โโ Expected output files โ Golden files
โโ Configuration?
โโ Many optional params โ Functional Options pattern
โโ Simple required params โ Constructor function
โโ External config โ struct + json/yaml/env tags
Verification
์ฝ๋ ์์ฑ ํ ๋ฐ๋์ ์คํ:
go build ./...
go test ./... -v
go vet ./...
golangci-lint run
Output Template
When implementing Go features, provide:
- Package structure and organization
- Core types (structs, interfaces, error types)
- Implementation with proper error handling
- Test file with table-driven tests
- Brief explanation of Go-specific patterns used