Golang Mastery (Senior → Principal)
Operate
- Start by confirming: goal, scope, constraints (Go version, platform, deps), non-functional requirements (latency/throughput/SLO), and “done”.
- Prefer small, end-to-end changes with tests; keep diffs easy to review (unless the user asks otherwise).
- Stdlib-first and “boring” solutions by default; add dependencies only when constraints justify them.
- Explain tradeoffs briefly; keep output actionable (commands, file paths, checklists).
The goal is not “it works locally”, but “it survives production”: clear boundaries, observable behavior, secure defaults, and low ops cost.
Default Go Standards
- Keep packages cohesive; avoid “util” grab-bags; name packages by responsibility, not type.
- Export only what must be used externally; keep APIs minimal and stable.
- Use
context.Contextfor cancellation/timeouts at boundaries; passctxas first arg. - Return errors, do not log-and-return the same error; wrap with
%wfor context. - Avoid global state; prefer dependency injection via constructors and interfaces.
- Avoid premature interfaces; introduce interfaces at the consumer boundary.
- Concurrency: avoid shared mutable state; prefer channels for coordination, mutexes for invariants; always handle cancellation and shutdown.
“Bad vs Good” (common production pitfalls)
// ❌ BAD: log-and-return (double logging), no useful context
if err != nil {
slog.Error("create user failed", "err", err)
return err
}
// ✅ GOOD: log once at the boundary; wrap error with context
if err != nil {
return fmt.Errorf("create user: %w", err)
}
Workflow (Feature / Refactor / Bug)
- Reproduce or specify behavior (tests first if feasible).
- Sketch design: public API, package boundaries, data shapes, failure modes, concurrency model.
- Implement smallest slice end-to-end.
- Add/adjust tests and benchmarks (when performance-sensitive).
- Validate: formatting, vet, tests, race (when relevant).
- Review for production readiness: config, logging, metrics, timeouts, retries, shutdown.
Validation Commands
- Run
gofmt -w (go list -f '{{.Dir}}' ./...)(PowerShell:gofmt -w @(go list -f '{{.Dir}}' ./...)) and ensure no diffs remain. - Run
go test ./.... - Run
go test -race ./...for concurrent code or servers (where supported). - Run
go test -run TestName -count=1 ./pathto avoid cached results when debugging. - Run
go test -bench . -benchmem ./...for hotspots. - If available, run
golangci-lint run(orgolangci-lint run --fast-onlyduring local iteration). - If available, run
govulncheck ./...(orgovulncheck -test ./...) before release.
If you want PowerShell entrypoints:
- sanity:
scripts/go_sanity.ps1 - security/vuln:
scripts/go_security.ps1
Project Structure & Dependencies
See references/project-structure.md for pragmatic layouts by project size, dependency direction guidance, and package naming heuristics.
Tooling (Up-to-date defaults)
See references/tooling.md for a safe baseline linter set, handling false positives, and configuration patterns.
Advanced Topics (Production)
Use these when the project demands “senior+” rigor (many sections include ❌/✅ patterns):
- Arsitektur & boundaries: references/architecture.md
- Principal playbook (casebook + decision tree): references/principal-playbook.md
- Coding standards (review-required): references/coding-standards.md
- Anti-patterns & bug traps: references/anti-patterns.md
- Concurrency (race/leak/backpressure): references/concurrency.md
- Errors & taxonomy: references/errors.md
- HTTP API & status codes: references/http-api.md
- Frameworks (Gin/Fiber/Beego): references/frameworks.md
- Database & queries: references/database.md
- Query engineering (Postgres/SQLC): references/query-engineering.md
- Auth (sessions/JWT/OAuth2): references/auth.md
- Outbound HTTP & SSRF hardening: references/outbound-http.md
- Idempotency & outbox: references/idempotency-outbox.md
- Security: references/security.md
- Reliability (timeouts, retries, backpressure): references/reliability.md
- Observability (OTel, correlation): references/observability.md
- Log/trace correlation: references/log-correlation.md
- OTel bootstrap: references/otel-bootstrap.md
- Performance (pprof/trace/allocs): references/performance.md
- Testing advanced: references/testing-advanced.md
- Distributed systems: references/distributed-systems.md
- Examples (real-world skeleton): references/examples.md
- Patterns (DI/options/circuit-breaker): references/patterns.md
- Snippets (copy/paste-safe): references/snippets.md
Service/HTTP Defaults
- Set timeouts: server
ReadHeaderTimeout, clientTimeout/transport timeouts; avoid unbounded requests. - Always implement graceful shutdown: close listeners, stop accepting, drain, cancel contexts, waitgroups.
- Prefer structured logs; include request IDs; avoid logging secrets/PII.
- Add health endpoints (
/healthz,/readyz) and basic metrics hooks.
Docker & Release Defaults
See references/docker.md for secure, reproducible Docker patterns (multi-stage builds, non-root, no latest, health checks).
Data & Persistence Defaults
- Validate inputs at the boundary; normalize early.
- Make error taxonomy explicit (not found, conflict, invalid, unavailable).
- Prefer migrations and explicit schemas; keep transactional boundaries clear.
- Keep domain logic independent of transport (HTTP/GRPC/CLI) where feasible.
Debugging & Performance
- Use
pprofand benchmarks for performance claims; measure before/after. - Watch allocations; prefer
strings.Builder,bytes.Buffer, preallocation when proven necessary. - Avoid reflection-heavy paths in hot loops unless unavoidable.
Security Checklist (Minimum)
- Validate and bound untrusted input (size, depth, time).
- Use
crypto/randfor security tokens; never roll your own crypto. - Store secrets in env/secret managers; never log secrets.
- Prefer least privilege and explicit allowlists for network/file operations.
Library Selection (Practical)
See references/libraries.md for a conservative shortlist (stdlib-first) plus config/env decoding examples.
Code Review Checklist
See references/checklists.md and references/code-review.md for PR checklists (API, concurrency, testing, ops).
Snippets
See references/snippets.md for copy/paste-safe patterns (graceful shutdown, context plumbing, worker pools).
Scripts
scripts/go_sanity.ps1- runsgofmt,go test,go vet, optional-race, andgolangci-lintif installed.scripts/go_security.ps1- runsgovulncheck+ quick hardening checks (and optionalgosec/staticcheckif installed).scripts/init_project.py- bootstraps a clean Go project skeleton (optional).