golang-best-practices
Golang Best Practices (Meta-Skill)
Comprehensive Go code review skill coordinating 5 specialized domain skills for complete code audits.
[!NOTE] v2.0.0 Update: This skill now coordinates multiple focused domain skills. Use specific skills for targeted reviews or this meta-skill for comprehensive audits.
Available Skills
1. Concurrency Safety ✅
12 rules | Goroutines, channels, race conditions, deadlocks
Status: Active (v2.0.0)
Use when:
- Reviewing code with goroutines or channels
- Debugging race conditions or deadlocks
- Auditing concurrent data access
Trigger phrases: "Check for race conditions", "Review concurrency", "Find goroutine leaks"
2. Clean Architecture ✅
9 rules | Layer separation, dependency rules, gRPC patterns
Status: Active (v2.0.0)
Use when:
- Auditing service architecture
- Reviewing layered architecture compliance
- Ensuring proper dependency injection
Trigger phrases: "Audit architecture", "Check layer dependencies", "Review Clean Architecture"
3. Error Handling ✅
7 rules | Error wrapping, context, nil checks
Status: Active (v2.0.0)
Use when:
- Reviewing error propagation
- Checking context usage
- Auditing error handling patterns
Trigger phrases: "Review error handling", "Check error wrapping", "Verify context propagation"
4. Design Patterns ✅
13 rules | Code smells, refactoring, Gang of Four patterns
Status: Active (v2.0.0)
Use when:
- Refactoring complex code
- Reducing technical debt
- Applying design patterns
Trigger phrases: "Refactor this code", "Reduce complexity", "Apply design patterns"
5. Idiomatic Go ✅
6 rules | Go-specific idioms, interfaces, pointers
Status: Active (v2.0.0)
Use when:
- Ensuring idiomatic Go style
- Reviewing interface usage
- Optimizing pointer usage
Trigger phrases: "Is this idiomatic Go?", "Review Go style", "Check interface design"
When to Use This Meta-Skill
Use this meta-skill for:
- Complete codebase audits
- Pre-production reviews
- Unknown issue categories
- Comprehensive refactoring
For targeted reviews, use specific skills above (e.g., just concurrency-safety or clean-architecture).
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rule Count |
|---|---|---|---|---|
| 1 | Critical Issues | CRITICAL | critical- |
8 |
| 2 | High-Impact Patterns | HIGH | high- |
14 |
| 3 | Medium Improvements | MEDIUM | medium- |
21 |
| 4 | Architecture | ARCHITECTURE | arch- |
5 |
Quick Reference
1. Critical Issues (CRITICAL)
These prevent bugs, crashes, and production failures
critical-error-wrapping- Use %w for error wrapping, not %vcritical-defer-in-loop- Avoid defer in loops (resource leaks)critical-context-leak- Always defer cancel() after context creationcritical-error-shadow- Don't shadow err variable in nested scopescritical-goroutine-leak- Goroutines must have exit conditionscritical-race-condition- Protect shared state with mutex/channelscritical-channel-deadlock- Ensure paired send/receive operationscritical-close-panic- Sender closes channel, not receiver
2. High-Impact Patterns (HIGH)
Reliability and correctness improvements
high-pointer-receiver- Use pointer receivers for mutationshigh-context-propagation- Propagate context through call chainhigh-error-is-as- Use errors.Is/As instead of ==high-interface-nil- Check interface nil correctlyhigh-goroutine-unbounded- Limit concurrent goroutines (worker pool)high-channel-not-closed- Always close channels when donehigh-loop-variable-capture- Avoid closure over loop variableshigh-waitgroup-mismatch- Match Add() and Done() callshigh-business-logic-handler- Keep delivery layer thinhigh-business-logic-repository- No business logic in data layerhigh-constructor-creates-deps- Inject dependencies, don't createhigh-transaction-in-repository- Transactions belong in usecasehigh-god-object- Extract logic from 300+ line functionshigh-extract-method- Name complex code blocks with descriptive methods
3. Medium Improvements (MEDIUM)
Code quality and idioms
medium-interface-pollution- Keep interfaces small (<5 methods)medium-accept-interface-return-struct- API flexibility patternmedium-pointer-overuse- Don't overuse pointers for small typesmedium-directional-channels- Use send/receive-only channelsmedium-buffered-channel-size- Choose appropriate buffer sizemedium-select-default- Avoid busy-wait with selectmedium-fat-interface- Split large interfacesmedium-usecase-complexity- Move business logic to domain entitiesmedium-interface-in-implementation- Define interfaces where usedmedium-sentinel-error-usage- Use sentinel errors for stable categoriesmedium-primitive-obsession- Replace primitives with value objectsmedium-long-parameter-list- Use parameter objects for >5 paramsmedium-data-clumps- Extract repeated parameter groupsmedium-feature-envy- Move logic closer to datamedium-magic-constants- Replace magic numbers with named constantsmedium-builder-pattern- Fluent API for complex constructionmedium-factory-constructor- Validated object creationmedium-introduce-parameter-object- Group related parametersmedium-switch-to-strategy- Replace type switches with interfacesmedium-middleware-decorator- Decorator pattern for http.Handlermedium-law-of-demeter- Reduce coupling, avoid message chains
4. Architecture (ARCHITECTURE)
Clean Architecture compliance for gRPC/usecase/repository pattern
arch-domain-import-infra- Domain must not import infrastructurearch-concrete-dependency- Depend on interfaces, not concrete typesarch-repository-business-logic- Repositories do CRUD onlyarch-usecase-orchestration- Usecases orchestrate, entities decidearch-interface-segregation- Small, consumer-defined interfaces
How to Use
For Code Review
- Read the code file(s)
- Check against rules in priority order (Critical first)
- For each violation found, reference the specific rule file
- Provide exact line numbers and explanation
- Show corrected code example
For Refactoring
- Identify code smells matching detection patterns
- Apply fixes from corresponding rule files
- Verify no regressions introduced
- Run tests to confirm correctness
Accessing Detailed Rules
Each rule file contains:
- Brief explanation of why it matters
- Detection criteria (how to spot the issue)
- Incorrect code example with explanation
- Correct code example with explanation
- Impact assessment
- Additional context and references
Example:
rules/critical-error-wrapping.md
rules/high-pointer-receiver.md
Reference Guides
For deep dives on specific topics:
references/concurrency-deep-dive.md- Comprehensive concurrency patternsreferences/error-handling-guide.md- Complete error handling strategiesreferences/testing-strategies.md- Go testing best practices
Common Usage Patterns
Review entire file:
Review this Go file for anti-patterns and suggest improvements
Focus on specific category:
Check this code for concurrency issues (CRITICAL level)
Architecture audit:
Verify this service follows Clean Architecture principles
Performance optimization:
Find performance issues in this Go code
Trigger Phrases
For comprehensive audits (uses this meta-skill):
- "Review my Go code"
- "Check this Golang file"
- "Find Go anti-patterns"
- "Audit this Go service"
For domain-specific reviews (uses specific skills):
- "Check for race conditions" → concurrency-safety
- "Audit architecture" → clean-architecture
- "Review error handling" → error-handling
- "Refactor this code" → design-patterns
- "Is this idiomatic Go?" → idiomatic-go
Best Practices Philosophy
Based on research from authoritative sources:
Jon Bodner's Principles:
- Go is deliberately simple and explicit
- "Boring" code is good code - predictable and maintainable
- Understand the "why" behind language features
- Idiomatic Go prioritizes clarity over cleverness
Katherine Cox-Buday's Guidelines:
- Concurrency is not parallelism
- Channels are for communication, mutexes are for state
- Always have exit conditions for goroutines
- Context is the standard way to propagate cancellation
Clean Architecture (Uncle Bob):
- Dependencies point inward toward business logic
- Domain layer has no external dependencies
- Interfaces defined by consumers, not producers
- Separation of concerns across layers
Output Format
When reviewing code, use this format:
## Critical Issues Found: X
### [Rule Name] (Line Y)
**Issue**: Brief description
**Fix**: Suggested correction
**Example**:
```go
// Corrected code here
Medium Improvements: X
[Similar format for medium priority items]
## Notes
- Rules are evidence-based from authoritative Go books
- Detection patterns help identify issues programmatically
- All rules include working code examples
- Tailored for gRPC/usecase/repository architecture patterns