Table of Contents
🧩 Patterns¶
Idiomatic Go patterns and classic design patterns, each with a short explanation and a runnable demo. Promoted here from the journal once understood well enough to teach.
Categories¶
Idiomatic Go patterns¶
- Functional options (
func(*Config)) - Constructor injection / "accept interfaces, return structs"
- Error wrapping & sentinel errors
contextpropagation & cancellation- Worker pool · fan-in/fan-out · pipeline · semaphore (bounded concurrency)
errgroupfor fan-out-with-errors- Table-driven tests
- Graceful shutdown (
signal.NotifyContext+Server.Shutdown)
Design patterns (Go flavor)¶
- Strategy (via interfaces / first-class funcs)
- Decorator / middleware (
func(http.Handler) http.Handler) - Factory · Singleton (
sync.Once) · Adapter · Observer - Repository · Ports & Adapters (hexagonal)
Structure¶
patterns/
├── functional-options/ main.go + README.md
├── worker-pool/ main.go + main_test.go + README.md
├── middleware/ …
└── …
Each folder: a README.md (what/when/why + trade-offs) and runnable code. Cross-link to the concurrency cheatsheet and the project that uses the pattern.
| Pattern | Category | Used in |
|---|---|---|
| Worker pool | concurrency | crawler |
| Middleware | web | REST API |
| Ports & adapters | architecture | capstone |
⬅ README