Commit 6b3057fd by Percy Quispe Huarcaya

chore: refactor code

parent dbf8aafa
File added
---
name: golang-concurrency
description: "Golang concurrency design — goroutine lifecycle and leak prevention, channels and `select`, channel ownership and direction, `sync.Mutex`/`RWMutex`/`sync.Map`/`sync.Once`/atomics, `errgroup`, `singleflight`, worker pools, and fan-out/fan-in pipelines. Use when writing or reviewing concurrent Go code, when choosing between channels and mutexes, when protecting a shared map or counter, or when a goroutine has no clear exit. Not for defensive coding unrelated to concurrency such as nil panics, slice aliasing, or numeric overflow (→ See `samber/cc-skills-golang@golang-safety` skill), and not for debugging a specific hung, crashing, or racing program after the fact (→ See `samber/cc-skills-golang@golang-troubleshooting` skill)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.2.1"
openclaw:
emoji: "⚡"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion
paths:
- "**/*.go"
---
**Persona:** You are a Go concurrency engineer. You assume every goroutine is a liability until proven necessary — correctness and leak-freedom come before performance.
**Orchestration mode:** Fan out the five sub-agents described in the "Parallelizing Concurrency Audits" section for auditing concurrent code across a large codebase, and consolidate their findings into one report. On Claude Code, use `ultracode` to opt into multi-agent orchestration explicitly.
**Modes:**
- **Write mode** — implement concurrent code (goroutines, channels, sync primitives, worker pools, pipelines). Follow the sequential instructions below.
- **Review mode** — reviewing a PR's concurrent code changes. Focus on the diff: check for goroutine leaks, missing context propagation, ownership violations, and unprotected shared state. Sequential.
- **Audit mode** — auditing existing concurrent code across a codebase. Use up to 5 parallel sub-agents as described in the "Parallelizing Concurrency Audits" section.
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-concurrency` skill takes precedence.
# Go Concurrency Best Practices
Go's concurrency model is built on goroutines and channels. Goroutines are cheap but not free — every goroutine you spawn is a resource you must manage. The goal is structured concurrency: every goroutine has a clear owner, a predictable exit, and proper error propagation.
## Core Principles
1. **Every goroutine must have a clear exit** — without a shutdown mechanism (context, done channel, WaitGroup), they leak and accumulate until the process crashes
2. **Share memory by communicating** — channels transfer ownership explicitly; mutexes protect shared state but make ownership implicit
3. **Send copies, not pointers** on channels — sending pointers creates invisible shared memory, defeating the purpose of channels
4. **Only the sender closes a channel** — closing from the receiver side panics if the sender writes after close
5. **Specify channel direction** (`chan<-`, `<-chan`) — the compiler prevents misuse at build time
6. **Default to unbuffered channels** — larger buffers mask backpressure; use them only with measured justification
7. **Always include `ctx.Done()` in select** — without it, goroutines leak after caller cancellation
8. **Avoid repeated `time.After` in hot loops** — each call allocates a timer and creates unnecessary churn; use `time.NewTimer` + `Reset` for long-running loops
9. **Track goroutine leaks in tests** with `go.uber.org/goleak`
For detailed channel/select code examples, see [Channels and Select Patterns](references/channels-and-select.md).
## Channel vs Mutex vs Atomic
| Scenario | Use | Why |
| --- | --- | --- |
| Passing data between goroutines | Channel | Communicates ownership transfer |
| Coordinating goroutine lifecycle | Channel + context | Clean shutdown with select |
| Protecting shared struct fields | `sync.Mutex` / `sync.RWMutex` | Simple critical sections |
| Simple counters, flags | `sync/atomic` | Lock-free, lower overhead |
| Many readers, few writers on a map | `sync.Map` | Optimized for read-heavy workloads. **Concurrent map read/write causes a hard crash** |
| Caching expensive computations | `sync.Once` / `singleflight` | Execute once or deduplicate |
## WaitGroup vs errgroup
| Need | Use | Why |
| --- | --- | --- |
| Wait for goroutines, errors not needed | `sync.WaitGroup` | Fire-and-forget |
| Wait + collect first error | `errgroup.Group` | Error propagation |
| Wait + cancel siblings on first error | `errgroup.WithContext` | Context cancellation on error |
| Wait + limit concurrency | `errgroup.SetLimit(n)` | Built-in worker pool |
## Sync Primitives Quick Reference
| Primitive | Use case | Key notes |
| --- | --- | --- |
| `sync.Mutex` | Protect shared state | Keep critical sections short; never hold across I/O |
| `sync.RWMutex` | Many readers, few writers | Never upgrade RLock to Lock (deadlock) |
| `sync/atomic` | Simple counters, flags | Prefer typed atomics (Go 1.19+): `atomic.Int64`, `atomic.Bool` |
| `sync.Map` | Concurrent map, read-heavy | No explicit locking; use `RWMutex`+map when writes dominate |
| `sync.Pool` | Reuse temporary objects | Always `Reset()` before `Put()`; reduces GC pressure |
| `sync.Once` | One-time initialization | Go 1.21+: `OnceFunc`, `OnceValue`, `OnceValues` |
| `sync.WaitGroup` | Waiting for simple goroutines | Go 1.25+: prefer `wg.Go(func(){ ... })` for fire-and-wait tasks that do not panic and do not need error propagation. For Go <1.25 use `Add`/`Done`. For errors/cancellation/limits, use `errgroup` with context. |
| `x/sync/singleflight` | Deduplicate concurrent calls | Cache stampede prevention |
| `x/sync/errgroup` | Goroutine group + errors | `SetLimit(n)` replaces hand-rolled worker pools |
For detailed examples and anti-patterns, see [Sync Primitives Deep Dive](references/sync-primitives.md).
## Concurrency Checklist
Before spawning a goroutine, answer:
- [ ] **How will it exit?** — context cancellation, channel close, or explicit signal
- [ ] **Can I signal it to stop?** — pass `context.Context` or done channel
- [ ] **Can I wait for it?** — `sync.WaitGroup` or `errgroup`
- [ ] **Who owns the channels?** — creator/sender owns and closes
- [ ] **Should this be synchronous instead?** — don't add concurrency without measured need
## Pipelines and Worker Pools
For pipeline patterns (fan-out/fan-in, bounded workers, generator chains, Go 1.23+ iterators, `samber/ro`), see [Pipelines and Worker Pools](references/pipelines.md).
## Parallelizing Concurrency Audits
When auditing concurrency across a large codebase, use up to 5 parallel sub-agents:
1. Find all goroutine spawns (`go func`, `go method`) and verify shutdown mechanisms
2. Search for mutable globals and shared state without synchronization
3. Audit channel usage — ownership, direction, closure, buffer sizes
4. Find `time.After` in loops, missing `ctx.Done()` in select, unbounded spawning
5. Check mutex usage, `sync.Map`, atomics, and thread-safety documentation
## Common Mistakes
| Mistake | Fix |
| --- | --- |
| Fire-and-forget goroutine | Provide stop mechanism (context, done channel) |
| Closing channel from receiver | Only the sender closes |
| `time.After` in hot loop | Reuse `time.NewTimer` + `Reset` |
| Missing `ctx.Done()` in select | Always select on context to allow cancellation |
| Unbounded goroutine spawning | Use `errgroup.SetLimit(n)` or semaphore |
| Sharing pointer via channel | Send copies or immutable values |
| `wg.Add` inside goroutine | Call `Add` before `go` — `Wait` may return early otherwise |
| Forgetting `-race` in CI | Always run `go test -race ./...` |
| Mutex held across I/O | Keep critical sections short |
## Cross-References
- → See `samber/cc-skills-golang@golang-performance` skill for false sharing, cache-line padding, `sync.Pool` hot-path patterns
- → See `samber/cc-skills-golang@golang-context` skill for cancellation propagation and timeout patterns
- → See `samber/cc-skills-golang@golang-safety` skill for concurrent map access and race condition prevention
- → See `samber/cc-skills-golang@golang-troubleshooting` skill for debugging goroutine leaks and deadlocks
- → See `samber/cc-skills-golang@golang-design-patterns` skill for graceful shutdown patterns
- → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines
### Goroutine leak profile
The goroutine leak profile (experimental behind `GOEXPERIMENT=goroutineleakprofile` in Go 1.26) is generally available in `runtime/pprof` since Go 1.27 — no build flag required. It is a useful production-oriented leak signal alongside the existing tools below.
```bash
curl http://localhost:6060/debug/pprof/goroutineleak?debug=2
go tool pprof http://localhost:6060/debug/pprof/goroutineleak
```
Keep existing tools:
- tests: `go.uber.org/goleak`
- runtime count: `runtime.NumGoroutine()`
- stack dump: `/debug/pprof/goroutine?debug=2`
- race checks: `go test -race ./...`
## References
- [Go Concurrency Patterns: Pipelines](https://go.dev/blog/pipelines)
- [Effective Go: Concurrency](https://go.dev/doc/effective_go#concurrency)
[
{
"id": 1,
"name": "time-after-in-select-loop",
"description": "Tests whether the model avoids time.After inside a select loop and uses time.NewTimer with Reset instead",
"prompt": "I have a Go worker that reads from a channel and needs a 5-second inactivity timeout. If nothing arrives for 5 seconds, it should log and continue waiting. Write the select loop.",
"trap": "Without the skill, the model uses time.After(5*time.Second) inside the for/select loop, creating repeated timer allocations/churn instead of reusing a timer",
"assertions": [
{ "id": "1.1", "text": "Does NOT use time.After inside the loop body" },
{
"id": "1.2",
"text": "Creates time.NewTimer (or time.NewTicker) outside the loop"
},
{
"id": "1.3",
"text": "Calls timer.Reset() after handling a message or timeout"
},
{
"id": "1.4",
"text": "Calls timer.Stop() (or defers it) to clean up the timer"
},
{
"id": "1.5",
"text": "For Go 1.23+, does not use the old stale-drain pattern; for Go <1.23 compatibility, drains before Reset when Stop reports a possible pending value"
}
]
},
{
"id": 2,
"name": "channel-closing-ownership",
"description": "Tests whether the model follows the rule that only the sender closes a channel, not the receiver",
"prompt": "I have a producer goroutine that sends items to a channel and a consumer goroutine that reads from it. The consumer knows when it has received enough items and wants to signal completion. How should I close the channel to stop the producer?",
"trap": "Without the skill, the model closes the channel from the consumer side, which panics if the producer writes after close",
"assertions": [
{
"id": "2.1",
"text": "Does NOT close the channel from the consumer/receiver side"
},
{
"id": "2.2",
"text": "Uses a separate signaling mechanism (done channel, context cancellation, or similar) for the consumer to tell the producer to stop"
},
{
"id": "2.3",
"text": "The producer is the one that closes the data channel (or it is closed by the channel creator/sender)"
},
{
"id": "2.4",
"text": "Explains the panic risk of closing a channel from the receiver side"
},
{
"id": "2.5",
"text": "The producer selects on the stop signal alongside its send operation"
}
]
},
{
"id": 3,
"name": "waitgroup-add-placement",
"description": "wg.Add before go statement; wg.Add(len(urls)) is preferred over per-goroutine Add(1) when count is known",
"prompt": "Review this Go code and identify all WaitGroup issues:\n\n```go\nfunc ProcessURLs(urls []string) []Result {\n var wg sync.WaitGroup\n results := make([]Result, len(urls))\n\n for i, url := range urls {\n go func(i int, url string) {\n wg.Add(1)\n defer wg.Done()\n results[i] = fetch(url)\n }(i, url)\n }\n\n wg.Wait()\n return results\n}\n```\n\nFix all issues. Also, is there a more efficient way to add to the WaitGroup when the number of goroutines is known upfront?",
"trap": "The most obvious bug (wg.Add inside goroutine) is well-known. The model should also catch the second issue: wg.Add(len(urls)) before the loop is more efficient than N separate wg.Add(1) calls (single atomic update vs N atomic updates). The model likely fixes the placement but may not suggest the batch Add optimization.",
"assertions": [
{
"id": "3.1",
"text": "Moves wg.Add(1) BEFORE the go statement — wg.Add inside the goroutine races with wg.Wait(), which can return before all goroutines have registered"
},
{
"id": "3.2",
"text": "Suggests using wg.Add(len(urls)) before the loop as a more efficient alternative — a single atomic operation instead of N separate wg.Add(1) calls in the loop"
},
{ "id": "3.3", "text": "Keeps defer wg.Done() inside the goroutine" },
{
"id": "3.4",
"text": "Notes the race condition: wg.Wait() could return before some goroutines have called wg.Add(1), causing ProcessURLs to return with goroutines still running"
}
]
},
{
"id": 4,
"name": "channel-direction-in-signatures",
"description": "Tests whether the model specifies channel direction (send-only, receive-only) in function signatures",
"prompt": "Write a Go pipeline with two functions: one that generates integers from a slice and sends them to a channel, and one that reads integers from a channel, doubles them, and sends to an output channel. Wire them together in main.",
"trap": "Without the skill, the model uses bidirectional chan int in function parameters instead of chan<- and <-chan",
"assertions": [
{
"id": "4.1",
"text": "The generator function returns <-chan int (receive-only for callers)"
},
{
"id": "4.2",
"text": "The doubler function accepts <-chan int as input parameter"
},
{
"id": "4.3",
"text": "The doubler function returns <-chan int (receive-only for callers)"
},
{
"id": "4.4",
"text": "Internally, channels are created as bidirectional but exposed as directional through return types"
},
{
"id": "4.5",
"text": "The producer (generator) closes its output channel with defer close(out)"
}
]
},
{
"id": 5,
"name": "unbuffered-channel-default",
"description": "Tests whether the model defaults to unbuffered channels and requires justification for buffered ones",
"prompt": "I need a channel to pass tasks from a dispatcher to a pool of workers in Go. Should I buffer it? If so, how large?",
"trap": "Without the skill, the model suggests an arbitrary large buffer (e.g., 100 or 1000) without justification or discussion of backpressure",
"assertions": [
{
"id": "5.1",
"text": "Recommends starting with unbuffered (or very small buffer like 0 or 1) as the default"
},
{
"id": "5.2",
"text": "Explains that large buffers mask backpressure problems"
},
{
"id": "5.3",
"text": "States that buffer size should be based on measured need, not arbitrary choice"
},
{
"id": "5.4",
"text": "Does NOT suggest a large arbitrary buffer (e.g., 100, 1000) without explaining the tradeoffs"
},
{
"id": "5.5",
"text": "Mentions that buffered channels hide the problem of slow consumers"
}
]
},
{
"id": 6,
"name": "send-copies-not-pointers",
"description": "Tests whether the model sends copies (not pointers) through channels to avoid shared memory",
"prompt": "I have a producer goroutine that creates Task structs and sends them to a channel for worker goroutines to process. The Task struct has fields like ID, Payload, and Status. Write the producer and consumer code.",
"trap": "Without the skill, the model sends *Task pointers through the channel, creating invisible shared memory that defeats the purpose of channels",
"assertions": [
{
"id": "6.1",
"text": "Sends Task values (not *Task pointers) through the channel, OR explicitly documents why pointers are safe in this case"
},
{
"id": "6.2",
"text": "The channel type is chan Task (value type) rather than chan *Task"
},
{
"id": "6.3",
"text": "Does not mutate the Task struct after sending it on the channel (or sends a copy)"
},
{
"id": "6.4",
"text": "If pointers are used, explicitly acknowledges the shared-memory risk and explains the mitigation"
}
]
},
{
"id": 7,
"name": "errgroup-vs-waitgroup-decision",
"description": "Tests whether the model chooses errgroup over WaitGroup when error handling is needed, and uses SetLimit for bounded concurrency",
"prompt": "Write a Go function that fetches data from 50 URLs concurrently. At most 10 should run at once. If any fetch fails, stop all remaining work and return the error.",
"trap": "Without the skill, the model builds a hand-rolled worker pool with WaitGroup + semaphore channel, missing errgroup.SetLimit which handles this natively",
"assertions": [
{
"id": "7.1",
"text": "Uses errgroup (golang.org/x/sync/errgroup) instead of sync.WaitGroup for error propagation"
},
{
"id": "7.2",
"text": "Uses errgroup.WithContext to cancel siblings on first error"
},
{
"id": "7.3",
"text": "Uses g.SetLimit(10) for bounded concurrency instead of a hand-rolled semaphore"
},
{
"id": "7.4",
"text": "Does NOT build a manual worker pool with channels and WaitGroup when errgroup suffices"
},
{
"id": "7.5",
"text": "Each goroutine checks ctx.Done() or uses the context from errgroup.WithContext"
}
]
},
{
"id": 8,
"name": "ctx-done-in-select",
"description": "Tests whether every select statement includes a ctx.Done() case to prevent goroutine leaks",
"prompt": "Write a Go function that reads from an input channel, transforms each item, and writes to an output channel. It should run as a goroutine.",
"trap": "Without the skill, the model writes a select with only channel operations but no ctx.Done() case, causing goroutine leaks on cancellation",
"assertions": [
{
"id": "8.1",
"text": "The function accepts a context.Context parameter"
},
{
"id": "8.2",
"text": "Every select statement includes a case <-ctx.Done(): return branch"
},
{
"id": "8.3",
"text": "Both the read from input channel AND the write to output channel are wrapped in select with ctx.Done()"
},
{
"id": "8.4",
"text": "The goroutine exits cleanly when context is cancelled"
},
{
"id": "8.5",
"text": "The output channel is closed when the goroutine exits (defer close)"
}
]
},
{
"id": 9,
"name": "sync-map-vs-rwmutex-decision",
"description": "Tests whether the model correctly chooses between sync.Map and RWMutex+map based on access patterns",
"prompt": "I need a concurrent cache in Go. Keys are strings, values are structs. The cache will have frequent writes from many goroutines updating the same keys, and reads happen about as often as writes. Which synchronization approach should I use?",
"trap": "Without the skill, the model recommends sync.Map because it sounds like 'concurrent map', but sync.Map is slower for write-heavy overlapping-key patterns",
"assertions": [
{
"id": "9.1",
"text": "Recommends sync.RWMutex + plain map over sync.Map for this write-heavy, overlapping-key pattern"
},
{
"id": "9.2",
"text": "Explains that sync.Map is optimized for write-once/read-many or disjoint key sets"
},
{
"id": "9.3",
"text": "Explains that for frequent writes with overlapping keys, RWMutex+map is faster"
},
{
"id": "9.4",
"text": "Does NOT unconditionally recommend sync.Map for any concurrent map scenario"
},
{
"id": "9.5",
"text": "Mentions that concurrent map read/write without synchronization causes a hard crash (not just a data race)"
}
]
},
{
"id": 10,
"name": "sync-pool-reset-before-put",
"description": "Tests whether the model resets objects before returning them to sync.Pool",
"prompt": "Write a Go function that uses sync.Pool to reuse bytes.Buffer objects for encoding JSON responses in an HTTP handler. Show the pool setup and the handler.",
"trap": "Without the skill, the model returns the buffer to the pool without calling Reset(), leading to dirty objects and data corruption",
"assertions": [
{
"id": "10.1",
"text": "Calls buf.Reset() BEFORE bufPool.Put(buf), not after Get()"
},
{
"id": "10.2",
"text": "Uses defer to ensure the buffer is returned to the pool even on error"
},
{
"id": "10.3",
"text": "Does not assume the object from Get() is clean/zeroed"
},
{ "id": "10.4", "text": "The pool's New function creates a new buffer" },
{
"id": "10.5",
"text": "Does not store persistent state in pooled objects"
}
]
},
{
"id": 11,
"name": "goroutine-panic-recovery",
"description": "Tests whether the model adds panic recovery at goroutine boundaries in production code",
"prompt": "Write a Go HTTP server that spawns a background goroutine per request to do async processing (e.g., sending a notification email). The main handler returns 202 Accepted immediately.",
"trap": "Without the skill, the model spawns go func() without recover(), so a panic in the background goroutine crashes the entire server process",
"assertions": [
{
"id": "11.1",
"text": "Adds defer func() { recover() }() or equivalent panic recovery inside the goroutine"
},
{
"id": "11.2",
"text": "Logs or handles the recovered panic (not just silently swallowed)"
},
{
"id": "11.3",
"text": "The goroutine has a shutdown mechanism (context, done channel, or similar)"
},
{
"id": "11.4",
"text": "Mentions that a panic in a goroutine crashes the entire process"
}
]
},
{
"id": 12,
"name": "singleflight-cache-stampede",
"description": "Tests whether the model uses singleflight to deduplicate concurrent requests for the same resource",
"prompt": "My Go service has an expensive database query for user profiles. Under load, hundreds of goroutines request the same user profile simultaneously, causing a thundering herd on the database. How should I solve this?",
"trap": "Without the skill, the model suggests only traditional caching (TTL-based) or a mutex, missing singleflight which deduplicates in-flight requests",
"assertions": [
{
"id": "12.1",
"text": "Recommends golang.org/x/sync/singleflight as the primary solution"
},
{
"id": "12.2",
"text": "Shows usage of group.Do(key, func) where key identifies the deduplicated resource"
},
{
"id": "12.3",
"text": "Explains that only one goroutine executes the function; others wait and share the result"
},
{
"id": "12.4",
"text": "May combine singleflight with a cache layer for TTL-based caching, but singleflight is the deduplication mechanism"
},
{
"id": "12.5",
"text": "Does NOT suggest only a plain mutex or only a TTL cache as the solution to thundering herd"
}
]
},
{
"id": 13,
"name": "iterator-vs-goroutine-pipeline",
"description": "Tests whether the model uses Go 1.23+ iterators for sequential CPU-bound transforms instead of goroutine+channel pipelines",
"prompt": "I have a Go 1.23+ project. I need to filter a slice of users to find active ones, then extract their email addresses. The slice is in-memory and processing is pure CPU. Should I use a goroutine pipeline with channels?",
"trap": "Without the skill, the model builds a goroutine+channel pipeline for a purely sequential, CPU-bound in-memory transformation where iterators are more appropriate",
"assertions": [
{
"id": "13.1",
"text": "Recommends against goroutine+channel pipeline for this purely sequential, in-memory transform"
},
{
"id": "13.2",
"text": "Suggests Go 1.23+ iterators (iter.Seq) or simple slice operations instead"
},
{
"id": "13.3",
"text": "Explains that goroutine+channel pipelines add overhead without benefit for sequential CPU-bound work"
},
{
"id": "13.4",
"text": "Mentions that goroutine pipelines are appropriate when stages involve I/O or need true parallelism"
},
{
"id": "13.5",
"text": "Does NOT build a multi-goroutine pipeline for this use case"
}
]
}
]
# Channels and Select Patterns
## Table of Contents
- [Goroutine Lifecycle](#goroutine-lifecycle)
- [Panic Recovery at Goroutine Boundaries](#panic-recovery-at-goroutine-boundaries)
- [Channel Direction](#channel-direction)
- [Channel Closing](#channel-closing)
- [Buffer Size](#buffer-size)
- [Select for Non-Blocking Communication](#select-for-non-blocking-communication)
- [Avoid Repeated `time.After` in Hot Loops](#avoid-repeated-timeafter-in-hot-loops)
## Goroutine Lifecycle
NEVER start a goroutine without knowing how it stops. Every goroutine MUST answer: **how will it stop?**
```go
// ✗ Bad — fire-and-forget, no way to stop or wait
func startWorker() {
go func() {
for {
doWork() // runs forever, leaks on shutdown
}
}()
}
// ✓ Good — goroutine respects context cancellation, caller can wait
func startWorker(ctx context.Context) *sync.WaitGroup {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
doWork(ctx)
}
}
}()
return &wg
}
```
### Panic Recovery at Goroutine Boundaries
A panic in a goroutine crashes the entire process. Always recover at goroutine boundaries in production code:
```go
go func() {
defer func() {
if r := recover(); r != nil {
// ...
}
}()
doWork(ctx)
}()
```
## Channel Direction
Specify direction in function signatures to prevent misuse at compile time:
```go
// ✗ Bad — caller could accidentally close or send on a receive-only channel
func consume(ch chan int) { ... }
// ✓ Good — compiler enforces correct usage
func produce(ch chan<- int) { ... } // send-only
func consume(ch <-chan int) { ... } // receive-only
```
## Channel Closing
Channels MUST be closed by the sender (producer), NEVER by the receiver — it causes a panic if the sender writes after close.
```go
// ✓ Good — producer closes when done
func generate(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // sender closes
for i := 0; ; i++ {
select {
case ch <- i:
case <-ctx.Done():
return
}
}
}()
return ch
}
```
## Buffer Size
| Size | When to use |
| --- | --- |
| 0 (unbuffered) | Default. Synchronizes sender and receiver — use when you need handoff guarantees |
| 1 | Signal channels (`done := make(chan struct{}, 1)`), or when sender must not block on a single pending item |
| N > 1 | Only with measured justification — document why N was chosen and what happens when the buffer fills |
```go
// ✓ Good — unbuffered for synchronous handoff
ch := make(chan Result)
// ✓ Good — buffered 1 for signal
done := make(chan struct{}, 1)
// ✗ Suspicious — arbitrary large buffer hides backpressure problems
// Give explanation in comments.
ch := make(chan Task, 1000) // why 1000? what if it fills?
```
## Select for Non-Blocking Communication
Use `select` to multiplex channel operations and always include `ctx.Done()` to prevent goroutine leaks:
```go
func process(ctx context.Context, in <-chan Task, out chan<- Result) {
for {
select {
case <-ctx.Done():
return
case task, ok := <-in:
if !ok {
return // channel closed
}
result := handle(ctx, task)
select {
case out <- result:
case <-ctx.Done():
return
}
}
}
}
```
## Avoid Repeated `time.After` in Hot Loops
```go
// ✗ Bad — creates a new timer on every iteration
for {
select {
case msg := <-ch:
handle(msg)
case <-time.After(5 * time.Second): // repeated allocation/churn
handleTimeout()
}
}
// ✓ Good (Go 1.23+) — reuse the timer
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
for {
select {
case msg := <-ch:
timer.Stop()
timer.Reset(5 * time.Second)
handle(msg)
case <-timer.C:
handleTimeout()
timer.Reset(5 * time.Second)
}
}
```
For Go <1.23, if `timer.Stop()` returns false, drain a possible stale value before `Reset`. In Go 1.23+, receiving from `timer.C` after `Stop` returns is guaranteed to block rather than receive a stale value.
# Pipelines and Worker Pools
## Table of Contents
- [Pipeline Pattern](#pipeline-pattern)
- [Fan-Out / Fan-In](#fan-out--fan-in)
- [Worker Pool with errgroup](#worker-pool-with-errgroup)
- [Bounded Concurrency with Semaphore](#bounded-concurrency-with-semaphore)
- [Pipeline Alternatives](#pipeline-alternatives)
- [Go 1.23+ Iterators (range-over-func)](#go-123-iterators-range-over-func)
- [samber/ro](#samberro)
- [Goroutine Leak Detection](#goroutine-leak-detection)
- [Common Pipeline Mistakes](#common-pipeline-mistakes)
## Pipeline Pattern
A pipeline is a series of stages connected by channels, where each stage is a goroutine (or group of goroutines) that:
1. Receives values from an upstream channel
2. Processes each value
3. Sends results to a downstream channel
```go
// Stage 1: Generate integers
func generate(ctx context.Context, nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
select {
case out <- n:
case <-ctx.Done():
return
}
}
}()
return out
}
// Stage 2: Square each integer
func square(ctx context.Context, in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
select {
case out <- n * n:
case <-ctx.Done():
return
}
}
}()
return out
}
// Usage
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch := generate(ctx, 2, 3, 4)
results := square(ctx, ch)
for v := range results {
fmt.Println(v) // 4, 9, 16
}
}
```
**Key rules for pipelines**:
- Pipeline stages MUST accept and respect context cancellation — every stage must select on `ctx.Done()` to avoid goroutine leaks on early cancellation
- The producer (first stage) closes its output channel; each subsequent stage closes its own output
- NEVER create unbounded goroutines in pipeline stages
- Use unbuffered channels unless you have measured throughput needs
## Fan-Out / Fan-In
**Fan-out**: multiple goroutines read from the same channel to parallelize CPU-bound work. **Fan-in**: multiple channels are merged into a single output channel.
```go
// Fan-out: N workers reading from the same input channel
func fanOut(ctx context.Context, in <-chan Task, workers int) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case task, ok := <-in:
if !ok {
return
}
select {
case out <- process(ctx, task):
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
```go
// Fan-in: merge multiple channels into one
func fanIn(ctx context.Context, channels ...<-chan Result) <-chan Result {
out := make(chan Result)
var wg sync.WaitGroup
for _, ch := range channels {
wg.Add(1)
go func(c <-chan Result) {
defer wg.Done()
for v := range c {
select {
case out <- v:
case <-ctx.Done():
return
}
}
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
return out
}
```
## Worker Pool with errgroup
Fan-out workers SHOULD use `errgroup.SetLimit` for bounded concurrency. For most use cases, `errgroup.SetLimit` replaces hand-rolled worker pools:
```go
func processAll(ctx context.Context, tasks []Task) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10) // max 10 concurrent workers
for _, task := range tasks {
g.Go(func() error {
return process(ctx, task)
})
}
return g.Wait()
}
```
Use a hand-rolled worker pool only when you need:
- Per-worker state (connections, buffers)
- Custom backpressure or priority scheduling
- Graceful draining with in-flight task completion
## Bounded Concurrency with Semaphore
When you need fine-grained concurrency control without errgroup:
```go
func processAll(ctx context.Context, items []Item) error {
sem := make(chan struct{}, 10) // semaphore of 10
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
sem <- struct{}{} // acquire
go func(item Item) {
defer wg.Done()
defer func() { <-sem }() // release
process(ctx, item)
}(item)
}
wg.Wait()
return nil
}
```
Prefer `errgroup.SetLimit` over this pattern when error propagation is needed.
## Pipeline Alternatives
### Go 1.23+ Iterators (range-over-func)
For in-process data transformations that do not need concurrency, iterators avoid the overhead of goroutines and channels:
```go
func Filter[T any](seq iter.Seq[T], pred func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range seq {
if pred(v) {
if !yield(v) {
return
}
}
}
}
}
func Map[T, U any](seq iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for v := range seq {
if !yield(f(v)) {
return
}
}
}
}
```
Use iterators when:
- Processing is CPU-bound and does not benefit from parallelism
- You want lazy evaluation without goroutine overhead
- The data source is already sequential (slice, database cursor)
Use goroutine+channel pipelines when:
- Stages involve I/O (network, disk) that benefits from concurrency
- You need true parallelism across CPU cores
- Stages have different throughput characteristics
### samber/ro
`samber/ro` provides a fluent, type-safe pipeline API for read-only collections:
```go
import "github.com/samber/ro"
emails, _ := ro.Collect( // ignore error
ro.Pipe(
ro.FromSlice(users),
ro.Filter(func(u User) bool { return u.Active }),
ro.Map(func(u User) string { return u.Email }),
),
)
```
Use `samber/ro` for sequential data transformations that benefit from a fluent API. It might also support parallel processing if needed.
## Goroutine Leak Detection
Goroutine leaks SHOULD be detected with goleak in tests. Use `go.uber.org/goleak` in `TestMain` to catch leaked goroutines across all tests:
```go
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
```
## Common Pipeline Mistakes
| Mistake | Fix |
| --- | --- |
| Missing `ctx.Done()` in pipeline stage | Always select on context to allow cancellation |
| Not closing output channel | Producer must `defer close(out)` |
| Unbounded goroutine spawning | Use `errgroup.SetLimit` or a semaphore |
| Sending mutable data through channel | Send copies or immutable values |
| Blocking send without select | Wrap channel sends in select with `ctx.Done()` |
→ See `samber/cc-skills-golang@golang-concurrency` skill for sync primitives and channel patterns.
# Sync Primitives Deep Dive
## Table of Contents
- [sync.Mutex](#syncmutex)
- [Embedding Convention](#embedding-convention)
- [sync.RWMutex](#syncrwmutex)
- [sync/atomic](#syncatomic)
- [sync.Map](#syncmap)
- [sync.Pool](#syncpool)
- [sync.Once](#synconce)
- [sync.WaitGroup](#syncwaitgroup)
- [Go 1.25+: `wg.Go`](#go-125-wggo)
- [Go <1.25 fallback](#go-125-fallback)
- [golang.org/x/sync/singleflight](#golangorgxsyncsingleflight)
- [golang.org/x/sync/errgroup](#golangorgxsyncerrgroup)
- [Bounded Concurrency with SetLimit](#bounded-concurrency-with-setlimit)
## sync.Mutex
Protects shared state with exclusive access. MUST hold the lock for the shortest time possible — NEVER hold a mutex across I/O, network calls, or channel operations.
```go
type SafeCache struct {
mu sync.Mutex
items map[string]string
}
func (c *SafeCache) Get(key string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.items[key]
return v, ok
}
func (c *SafeCache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
}
```
### Embedding Convention
Embed the mutex as an unexported field, placed directly above the fields it protects:
```go
type Registry struct {
mu sync.Mutex // protects entries
entries map[string]Entry
}
```
## sync.RWMutex
SHOULD be used when reads greatly outnumber writes. Multiple goroutines can hold `RLock` simultaneously; `Lock` is exclusive.
```go
type Config struct {
mu sync.RWMutex
values map[string]string
}
func (c *Config) Get(key string) string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.values[key]
}
func (c *Config) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.values[key] = value
}
```
**Pitfall**: Do not upgrade RLock to Lock — this deadlocks. Release RLock first, then acquire Lock.
## sync/atomic
Lock-free operations for simple values. SHOULD be preferred over Mutex for simple counter operations. Faster than mutex for low-contention counters and flags.
```go
// ✓ Good — atomic for a simple counter
var requestCount atomic.Int64
func handleRequest() {
requestCount.Add(1)
}
func getCount() int64 {
return requestCount.Load()
}
```
```go
// ✓ Good — atomic.Bool for a shutdown flag
var shuttingDown atomic.Bool
func shutdown() {
shuttingDown.Store(true)
}
func isRunning() bool {
return !shuttingDown.Load()
}
```
Go 1.19+ provides typed atomics (`atomic.Int64`, `atomic.Bool`, `atomic.Pointer[T]`) — prefer these over raw `atomic.AddInt64`/`atomic.LoadInt64`.
## sync.Map
SHOULD only be used for write-once/read-many patterns. Optimized for two common patterns: (1) keys are written once and read many times, (2) multiple goroutines read/write disjoint key sets. For other patterns, a plain `map` + `sync.RWMutex` is faster.
```go
var cache sync.Map
func Get(key string) (any, bool) {
return cache.Load(key)
}
func Set(key string, value any) {
cache.Store(key, value)
}
func GetOrSet(key string, compute func() any) any {
if v, ok := cache.Load(key); ok {
return v
}
v, _ := cache.LoadOrStore(key, compute())
return v
}
```
**When NOT to use `sync.Map`**: when you need to iterate, get the length, or when writes are frequent and keys overlap heavily. Use `sync.RWMutex` + `map` instead.
## sync.Pool
Reuse temporary objects to reduce GC pressure. MUST NOT store pointers to stack-allocated objects. Objects in the pool may be reclaimed at any GC cycle — do not store persistent state.
```go
var bufPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func process(data []byte) string {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
buf.Write(data)
// ... transform ...
return buf.String()
}
```
**Rules**:
- Always `Reset()` before `Put()` — returning dirty objects causes bugs
- Do not assume an object from `Get()` is zeroed — the `New` func only runs if the pool is empty
- Best for short-lived, frequently allocated objects (buffers, encoders, temporary structs)
## sync.Once
MUST be used for one-time initialization. Execute exactly once, regardless of how many goroutines call it concurrently. Thread-safe by design.
```go
type DBClient struct {
initOnce sync.Once
closeOnce sync.Once
conn *sql.DB
}
func (c *DBClient) getConn() *sql.DB {
c.initOnce.Do(func() {
var err error
c.conn, err = sql.Open("postgres", dsn)
if err != nil {
panic(fmt.Sprintf("db init: %v", err))
}
})
return c.conn
}
func (c *DBClient) Close() error {
var err error
c.closeOnce.Do(func() {
err = c.conn.Close()
})
return err
}
```
Go 1.21+ also provides `sync.OnceFunc`, `sync.OnceValue`, and `sync.OnceValues` for simpler use cases:
```go
var loadConfig = sync.OnceValue(func() *Config {
cfg, err := parseConfig("config.yaml")
if err != nil {
panic(err)
}
return cfg
})
// Usage: cfg := loadConfig()
```
## sync.WaitGroup
Use `sync.WaitGroup` when you only need to wait for a set of goroutines to finish.
### Go 1.25+: `wg.Go`
`WaitGroup.Go` starts a goroutine, adds it to the group, and removes it from the group when the function returns.
```go
func processAll(items []Item) {
var wg sync.WaitGroup
for _, item := range items {
// Go 1.22+ loop variables are per-iteration when the module has `go 1.22+`.
// Do not add `item := item` solely for closure capture in modern modules.
wg.Go(func() {
process(item)
})
}
wg.Wait()
}
```
Rules:
- `WaitGroup.Go` is Go 1.25+, not Go 1.24.
- The function passed to `wg.Go` must not panic.
- `WaitGroup` does not propagate errors and does not cancel siblings.
- For first-error-wins, cancellation, concurrency limits, or returned values, use `golang.org/x/sync/errgroup`.
**Benefits of `wg.Go()`**:
- No manual `Add`/`Done` bookkeeping
- Lower risk of `Add`/`Wait` ordering bugs
- Cleaner API for simple fire-and-wait work
**When to use**: Go 1.25+ projects for simple goroutines that must all finish, do not return errors, do not need cancellation, and must not panic. Use `errgroup` when work returns errors, needs cancellation, limits, or first-error behavior.
### Go <1.25 fallback
```go
func processAll(ctx context.Context, items []Item) {
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1) // Add BEFORE go
go func(item Item) {
defer wg.Done()
process(ctx, item)
}(item)
}
wg.Wait() // blocks until all goroutines finish
}
```
```go
// ✗ Bad — Add inside the goroutine (race: Wait may return before Add runs)
go func() {
wg.Add(1)
defer wg.Done()
process(item)
}()
```
## golang.org/x/sync/singleflight
Deduplicates concurrent calls for the same key. When multiple goroutines request the same resource simultaneously, only one executes; the rest wait and share the result.
```go
var group singleflight.Group
func GetUser(ctx context.Context, id string) (*User, error) {
v, err, _ := group.Do(id, func() (any, error) {
// Only one goroutine executes this for a given id
return db.QueryUser(ctx, id)
})
if err != nil {
return nil, err
}
return v.(*User), nil
}
```
**Use cases**: cache stampede prevention, deduplicating expensive lookups (DB, API), rate-limited external service calls.
## golang.org/x/sync/errgroup
Goroutine group with error propagation. Returns the first error from any goroutine. With `WithContext`, cancels remaining goroutines on first error.
```go
func fetchAll(ctx context.Context, urls []string) ([]Response, error) {
g, ctx := errgroup.WithContext(ctx) // cancel siblings on first error
results := make([]Response, len(urls))
for i, url := range urls {
g.Go(func() error {
resp, err := fetch(ctx, url)
if err != nil {
return fmt.Errorf("fetching %s: %w", url, err)
}
results[i] = resp // safe: each goroutine writes to its own index
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return results, nil
}
```
### Bounded Concurrency with SetLimit
SHOULD use `SetLimit` to bound concurrency and avoid unbounded goroutine spawning.
```go
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(10) // at most 10 goroutines run concurrently
for _, task := range tasks {
g.Go(func() error {
return process(ctx, task)
})
}
return g.Wait()
```
This replaces hand-rolled worker pools for most use cases.
→ See `samber/cc-skills-golang@golang-concurrency` skill for high-level patterns and decision trees.
---
name: golang-design-patterns
description: "Idiomatic Golang design patterns — functional options, constructor APIs, `init()` and global-state avoidance, enums, panic vs error decisions, resource management and lifecycle, graceful shutdown, timeouts and retries, streaming and iterators, and architecture styles (clean, hexagonal, DDD, flat). Apply when choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem. Not for wiring a DI container or comparing DI libraries (→ See `samber/cc-skills-golang@golang-dependency-injection` skill), nor for error wrapping, `errors.Is`/`As`, or logging mechanics (→ See `samber/cc-skills-golang@golang-error-handling` skill)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.2.1"
openclaw:
emoji: "🏗"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion
paths:
- "**/*.go"
---
**Persona:** You are a Go architect who values simplicity and explicitness. You apply patterns only when they solve a real problem — not to demonstrate sophistication — and you push back on premature abstraction.
**Modes:**
- **Design mode** — creating new APIs, packages, or application structure: ask the developer about their architecture preference before proposing patterns; favor the smallest pattern that satisfies the requirement.
- **Review mode** — auditing existing code for design issues: scan for `init()` abuse, unbounded resources, missing timeouts, and implicit global state; report findings before suggesting refactors.
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-design-patterns` skill takes precedence.
# Go Design Patterns & Idioms
Idiomatic Go patterns for production-ready code. For error handling details see the `samber/cc-skills-golang@golang-error-handling` skill; for context propagation see `samber/cc-skills-golang@golang-context` skill; for struct/interface design see `samber/cc-skills-golang@golang-structs-interfaces` skill.
## Best Practices Summary
1. Constructors SHOULD use **functional options** — they scale better as APIs evolve (one function per option, no breaking changes)
2. Functional options MUST **return an error** if validation can fail — catch bad config at construction, not at runtime
3. **Avoid `init()`** — runs implicitly, cannot return errors, makes testing unpredictable. Use explicit constructors
4. Enums SHOULD **start at 1** (or Unknown sentinel at 0) — Go's zero value silently passes as the first enum member
5. Error cases MUST be **handled first** with early return — keep happy path flat
6. **Panic is for bugs, not expected errors** — callers can handle returned errors; panics crash the process
7. **`defer Close()` immediately after opening** — later code changes can accidentally skip cleanup
8. **`runtime.AddCleanup`** over `runtime.SetFinalizer` — finalizers are unpredictable and can resurrect objects
9. Every external call SHOULD **have a timeout** — a slow upstream hangs your goroutine indefinitely
10. **Limit everything** (pool sizes, queue depths, buffers) — unbounded resources grow until they crash
11. Retry logic MUST **check context cancellation** between attempts
12. **Use `strings.Builder`** for concatenation in loops → see `samber/cc-skills-golang@golang-code-style`
13. string vs []byte: **use `[]byte` for mutation and I/O**, `string` for display and keys — conversions allocate
14. Iterators (Go 1.23+): **use for lazy evaluation** — avoid loading everything into memory
15. **Stream large transfers** — loading millions of rows causes OOM; stream keeps memory constant
16. `//go:embed` for **static assets** — embeds at compile time, eliminates runtime file I/O errors
17. **Use `crypto/rand`** for keys/tokens — `math/rand` is predictable → see `samber/cc-skills-golang@golang-security`
18. Regexp MUST be **compiled once at package level** — compilation is O(n) and allocates
19. Compile-time interface checks: **`var _ Interface = (*Type)(nil)`**
20. **A little recode > a big dependency** — each dep adds attack surface and maintenance burden
21. **Design for testability** — accept interfaces, inject dependencies
## Constructor Patterns: Functional Options vs Builder
### Functional Options (Preferred)
```go
type Server struct {
addr string
readTimeout time.Duration
writeTimeout time.Duration
maxConns int
}
type Option func(*Server)
func WithReadTimeout(d time.Duration) Option {
return func(s *Server) { s.readTimeout = d }
}
func WithWriteTimeout(d time.Duration) Option {
return func(s *Server) { s.writeTimeout = d }
}
func WithMaxConns(n int) Option {
return func(s *Server) { s.maxConns = n }
}
func NewServer(addr string, opts ...Option) *Server {
// Default options
s := &Server{
addr: addr,
readTimeout: 5 * time.Second,
writeTimeout: 10 * time.Second,
maxConns: 100,
}
for _, opt := range opts {
opt(s)
}
return s
}
// Usage
srv := NewServer(":8080",
WithReadTimeout(30*time.Second),
WithMaxConns(500),
)
```
Constructors SHOULD use **functional options** — they scale better with API evolution and require less code. Use builder pattern only if you need complex validation between configuration steps.
## Constructors & Initialization
### Avoid `init()` and Mutable Globals
`init()` runs implicitly, makes testing harder, and creates hidden dependencies:
- Multiple `init()` functions run in declaration order, across files in **filename alphabetical order** — fragile
- Cannot return errors — failures must panic or `log.Fatal`
- Runs before `main()` and tests — side effects make tests unpredictable
```go
// Bad — hidden global state
var db *sql.DB
func init() {
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
}
// Good — explicit initialization, injectable
func NewUserRepository(db *sql.DB) *UserRepository {
return &UserRepository{db: db}
}
```
### Enums: Start at 1
Zero values should represent invalid/unset state:
```go
type Status int
const (
StatusUnknown Status = iota // 0 = invalid/unset
StatusActive // 1
StatusInactive // 2
StatusSuspended // 3
)
```
### Compile Regexp Once
```go
// Good — compiled once at package level
var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
func ValidateEmail(email string) bool {
return emailRegex.MatchString(email)
}
```
### Use `//go:embed` for Static Assets
```go
import "embed"
//go:embed templates/*
var templateFS embed.FS
//go:embed version.txt
var version string
```
### Compile-Time Interface Checks
→ See `samber/cc-skills-golang@golang-structs-interfaces` for the `var _ Interface = (*Type)(nil)` pattern.
## Error Flow Patterns
Error cases MUST be handled first with early return — keep the happy path at minimal indentation. → See `samber/cc-skills-golang@golang-code-style` for the full pattern and examples.
### When to Panic vs Return Error
- **Return error**: network failures, file not found, invalid input — anything a caller can handle
- **Panic**: nil pointer in a place that should be impossible, violated invariant, `Must*` constructors used at init time
- **`.Close()` / `Flush()` errors**: read-only cleanup can often use `defer f.Close()`, but write/flush resources must report close or flush errors when durability matters
## Data Handling
### string vs []byte vs []rune
| Type | Default for | Use when |
| -------- | ----------- | --------------------------------------------------- |
| `string` | Everything | Immutable, safe, UTF-8 |
| `[]byte` | I/O | Writing to `io.Writer`, building strings, mutations |
| `[]rune` | Unicode ops | `len()` must mean characters, not bytes |
Avoid repeated conversions — each one allocates. Stay in one type until you need the other.
### Iterators & Streaming for Large Data
Use iterators (Go 1.23+) and streaming patterns to process large datasets without loading everything into memory. For large transfers between services (e.g., 1M rows DB to HTTP), stream to prevent OOM.
For code examples, see [Data Handling Patterns](references/data-handling.md).
## Resource Management
`defer Close()` immediately after opening — don't wait, don't forget:
```go
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // right here, not 50 lines later
rows, err := db.QueryContext(ctx, query)
if err != nil {
return err
}
defer rows.Close()
```
For graceful shutdown, resource pools, and `runtime.AddCleanup`, see [Resource Management](references/resource-management.md).
## Resilience & Limits
### Timeout Every External Call
```go
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
resp, err := httpClient.Do(req.WithContext(ctx))
```
### Retry & Context Checks
Retry logic MUST check `ctx.Err()` between attempts and use exponential/linear backoff via `select` on `ctx.Done()`. Long loops MUST check `ctx.Err()` periodically. → See `samber/cc-skills-golang@golang-context` skill.
## Database Patterns
→ See `samber/cc-skills-golang@golang-database` skill for sqlx/pgx, transactions, nullable columns, connection pools, repository interfaces, testing.
## Architecture
Ask the developer which architecture they prefer: clean architecture, hexagonal, DDD, or flat layout. Don't impose complex architecture on a small project.
Core principles regardless of architecture:
- **Keep domain pure** — no framework dependencies in the domain layer
- **Fail fast** — validate at boundaries, trust internal code
- **Make illegal states unrepresentable** — use types to enforce invariants
- **Respect 12-factor app** principles — → see `samber/cc-skills-golang@golang-project-layout`
## Detailed Guides
| Guide | Scope |
| --- | --- |
| [Architecture Patterns](references/architecture.md) | High-level principles, when each architecture fits |
| [Clean Architecture](references/clean-architecture.md) | Use cases, dependency rule, layered adapters |
| [Hexagonal Architecture](references/hexagonal-architecture.md) | Ports and adapters, domain core isolation |
| [Domain-Driven Design](references/ddd.md) | Aggregates, value objects, bounded contexts |
## Code Philosophy
- **Avoid repetitive code** — but don't abstract prematurely
- **Minimize dependencies** — a little recode > a big dependency
- **Design for testability** — accept interfaces, inject dependencies, keep functions pure
## Cross-References
- → See `samber/cc-skills-golang@golang-data-structures` skill for data structure selection, internals, and container/ packages
- → See `samber/cc-skills-golang@golang-error-handling` skill for error wrapping, sentinel errors, and the single handling rule
- → See `samber/cc-skills-golang@golang-structs-interfaces` skill for interface design and composition
- → See `samber/cc-skills-golang@golang-concurrency` skill for goroutine lifecycle and graceful shutdown
- → See `samber/cc-skills-golang@golang-context` skill for timeout and cancellation patterns
- → See `samber/cc-skills-golang@golang-project-layout` skill for architecture and directory structure
- → See `samber/cc-skills-golang@golang-refactoring` skill for safely staging a migration toward one of these patterns (options struct, DI, consumer-side interfaces) across an existing codebase
[
{
"id": 1,
"name": "functional-options-over-builder",
"description": "Tests whether the model recommends functional options (not builder pattern) as the preferred constructor pattern in Go, and whether options return errors for validation",
"prompt": "I need to create a Go HTTP server struct with optional configuration: read timeout, write timeout, max connections, TLS config, and a logger. Design the constructor API. The config will grow over time as we add features.",
"trap": "Without the skill, the model may default to a builder pattern, config struct, or positional arguments instead of functional options. It may also forget that options should return errors when validation can fail.",
"assertions": [
{
"id": "1.1",
"text": "Uses functional options pattern (Option type as func that modifies the struct)"
},
{
"id": "1.2",
"text": "Constructor accepts variadic ...Option parameter"
},
{
"id": "1.3",
"text": "Each option is a With* function returning an Option"
},
{
"id": "1.4",
"text": "Sets sensible defaults inside the constructor before applying options"
},
{
"id": "1.5",
"text": "Mentions that functional options should return an error if validation can fail, or demonstrates error-returning option variant"
}
]
},
{
"id": 2,
"name": "avoid-init-function",
"description": "Tests whether the model avoids init() for database initialization and uses explicit constructors instead",
"prompt": "I'm writing a Go web service. I want to set up the database connection pool when the application starts. Here's my approach:\n\n```go\nvar db *sql.DB\n\nfunc init() {\n var err error\n db, err = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n if err != nil {\n log.Fatal(err)\n }\n}\n```\n\nIs this a good pattern? How should I improve it?",
"trap": "Without the skill, the model may accept the init() pattern as fine or only suggest minor improvements. The skill explicitly warns against init() for hidden dependencies and testability issues.",
"assertions": [
{
"id": "2.1",
"text": "Explicitly recommends against using init() for database initialization"
},
{
"id": "2.2",
"text": "Mentions that init() makes testing harder or unpredictable"
},
{
"id": "2.3",
"text": "Mentions that init() cannot return errors (must panic or log.Fatal)"
},
{
"id": "2.4",
"text": "Suggests explicit constructor or initialization function (e.g. NewUserRepository(db))"
},
{
"id": "2.5",
"text": "Mentions that init() runs before main/tests creating hidden dependencies"
}
]
},
{
"id": 3,
"name": "enum-start-at-one",
"description": "Tests whether the model starts Go enums at 1 or uses an Unknown/Invalid sentinel at 0",
"prompt": "I need to define a Go enum for order status with values: pending, processing, shipped, delivered, cancelled. Write the type and constants using iota.",
"trap": "Without the skill, the model often starts the first meaningful enum value at 0 (iota), making the zero value silently pass as a valid status. The skill says enums SHOULD start at 1 or use an Unknown sentinel at 0.",
"assertions": [
{
"id": "3.1",
"text": "Zero value (iota = 0) is either skipped, named Unknown, Invalid, or Unspecified -- not a meaningful business value"
},
{
"id": "3.2",
"text": "First meaningful enum value starts at 1 or higher"
},
{
"id": "3.3",
"text": "Explains WHY: Go's zero value would silently pass as the first enum member if it were meaningful"
},
{ "id": "3.4", "text": "Uses a custom type (not raw int or string)" }
]
},
{
"id": 4,
"name": "panic-vs-error-judgment",
"description": "Tests whether the model correctly distinguishes when to panic vs return an error",
"prompt": "I'm implementing a configuration parser in Go. If the config file has an invalid format, should I panic or return an error? What about if a required field is missing? What about if a developer passes nil to a function that documents it must not be nil?",
"trap": "Without the skill, the model may be inconsistent about when to panic. The skill says panic is for bugs (violated invariants, impossible nil), not expected errors (invalid input, missing fields).",
"assertions": [
{
"id": "4.1",
"text": "Invalid config format: return error (caller can handle it)"
},
{
"id": "4.2",
"text": "Missing required field: return error (expected validation failure)"
},
{
"id": "4.3",
"text": "Nil passed to non-nil function: panic is acceptable (violated invariant, bug in caller)"
},
{
"id": "4.4",
"text": "Articulates the principle: panic is for bugs/invariant violations, errors are for expected failures"
},
{
"id": "4.5",
"text": "Mentions Must* constructor pattern as a valid panic use case (init-time convenience)"
}
]
},
{
"id": 5,
"name": "runtime-addcleanup-over-setfinalizer",
"description": "Tests whether the model recommends runtime.AddCleanup over runtime.SetFinalizer for Go 1.24+",
"prompt": "I have a Go struct that wraps a C resource handle (via cgo). When the Go object is garbage collected, I need to release the C handle. I'm using Go 1.24. What's the best approach for automatic cleanup?",
"trap": "Without the skill, the model almost always suggests runtime.SetFinalizer, which is the older and more well-known API. The skill specifically says to prefer runtime.AddCleanup (Go 1.24+).",
"assertions": [
{
"id": "5.1",
"text": "Recommends runtime.AddCleanup as the preferred approach"
},
{
"id": "5.2",
"text": "Mentions that AddCleanup supports multiple cleanups on the same object"
},
{
"id": "5.3",
"text": "Mentions that AddCleanup avoids object resurrection risk (cleanup receives a copy of the value, not the object)"
},
{
"id": "5.4",
"text": "Mentions that AddCleanup works even with cyclic references"
},
{
"id": "5.5",
"text": "Either warns against SetFinalizer or explains why AddCleanup is better"
}
]
},
{
"id": 6,
"name": "resource-pool-bounded-channel",
"description": "Tests whether the model uses bounded channel-based pools and emphasizes limiting resource pool sizes",
"prompt": "I need to implement a connection pool in Go for reusing database connections. I want it to be concurrent-safe and have a maximum size. Design the pool.",
"trap": "Without the skill, the model may use sync.Pool (wrong: not bounded, items can be evicted) or an unbounded slice with mutex. The skill says use channels with fixed capacity for bounded allocation.",
"assertions": [
{
"id": "6.1",
"text": "Uses a buffered channel (chan *Conn with fixed capacity) as the pool mechanism"
},
{ "id": "6.2", "text": "Pool has a maximum size / bounded capacity" },
{
"id": "6.3",
"text": "Get operation uses select with context for timeout/cancellation"
},
{
"id": "6.4",
"text": "Put operation handles pool-full case (discards excess connections)"
},
{
"id": "6.5",
"text": "Does NOT use sync.Pool as the primary pooling mechanism (sync.Pool has no size guarantee and items can be reclaimed)"
}
]
},
{
"id": 7,
"name": "graceful-shutdown-signal-notifycontext",
"description": "Tests whether the model uses signal.NotifyContext for graceful shutdown",
"prompt": "I'm building a Go HTTP server that needs to handle SIGINT and SIGTERM for graceful shutdown. Show me how to implement this properly.",
"trap": "Without the skill, the model may use a raw os.Signal channel with signal.Notify instead of signal.NotifyContext. The skill specifically says to use signal.NotifyContext.",
"assertions": [
{
"id": "7.1",
"text": "Uses signal.NotifyContext (not raw signal.Notify with a channel)"
},
{ "id": "7.2", "text": "Listens for both SIGINT and SIGTERM" },
{ "id": "7.3", "text": "Starts the HTTP server in a goroutine" },
{
"id": "7.4",
"text": "Creates a separate timeout context for the shutdown phase (e.g. context.WithTimeout for draining)"
},
{
"id": "7.5",
"text": "Closes other resources (DB, queues) after server shutdown"
}
]
},
{
"id": 8,
"name": "iterator-streaming-large-data",
"description": "Tests whether the model uses iterators/streaming instead of loading all data into memory for large datasets",
"prompt": "I need to export 2 million user records from a PostgreSQL database to a JSON HTTP response in Go. The users table has columns: id, name, email, created_at. Write the handler.",
"trap": "Without the skill, the model typically loads all rows into a []User slice, then json.Marshal the whole thing. The skill says to stream large transfers to prevent OOM.",
"assertions": [
{
"id": "8.1",
"text": "Does NOT load all 2M rows into a slice in memory"
},
{
"id": "8.2",
"text": "Streams the JSON response (writes records one at a time to the ResponseWriter)"
},
{
"id": "8.3",
"text": "Uses rows.Next() loop or iter.Seq2 iterator pattern"
},
{ "id": "8.4", "text": "Defers rows.Close() immediately after query" },
{
"id": "8.5",
"text": "Mentions OOM risk or memory concern as motivation for streaming"
}
]
},
{
"id": 9,
"name": "regexp-compile-once",
"description": "Tests whether the model compiles regexps at package level, not inside functions",
"prompt": "Write a Go function that validates email addresses using a regular expression. It will be called thousands of times per second in an HTTP handler.",
"trap": "Without the skill, the model often compiles the regexp inside the function on every call. The skill says regexp MUST be compiled once at package level.",
"assertions": [
{
"id": "9.1",
"text": "Compiles the regexp at package level (var emailRegex = regexp.MustCompile(...))"
},
{
"id": "9.2",
"text": "Does NOT compile the regexp inside the validation function"
},
{
"id": "9.3",
"text": "Uses regexp.MustCompile (not regexp.Compile) for package-level initialization"
},
{
"id": "9.4",
"text": "Explains WHY: compilation is O(n) and allocates, so doing it per-call is wasteful"
}
]
},
{
"id": 10,
"name": "architecture-right-sizing",
"description": "Tests whether the model avoids over-architecting small projects and asks for preferences",
"prompt": "I'm starting a new Go project: a CLI tool that reads a CSV file, transforms the data, and writes it to stdout. It will be about 200 lines of code. What architecture and directory structure should I use?",
"trap": "Without the skill, the model may suggest clean architecture, hexagonal patterns, handler/service/repository layers, or DI frameworks for a 200-line CLI. The skill says don't impose complex architecture on small projects.",
"assertions": [
{
"id": "10.1",
"text": "Recommends a flat or minimal structure (no multi-layer architecture)"
},
{
"id": "10.2",
"text": "Does NOT suggest clean architecture, hexagonal, DDD, or ports and adapters for a 200-line CLI"
},
{
"id": "10.3",
"text": "Does NOT suggest dependency injection frameworks"
},
{
"id": "10.4",
"text": "Structure has at most cmd/ and possibly internal/, not handler/service/repository layers"
},
{
"id": "10.5",
"text": "Mentions that architecture complexity should match project scope"
}
]
},
{
"id": 11,
"name": "hexagonal-vs-clean-architecture",
"description": "Tests whether the model correctly distinguishes hexagonal from clean architecture and when each applies",
"prompt": "I'm building a Go service (about 8K lines) that processes orders. It needs HTTP and gRPC entry points, plus a message consumer for async events. It talks to PostgreSQL, Stripe, and Redis. Should I use clean architecture or hexagonal architecture? Explain the difference and recommend one.",
"trap": "Without the skill, the model may conflate the two architectures or fail to identify that hexagonal is better when multiple entry points are needed. The skill has distinct guides for each.",
"assertions": [
{
"id": "11.1",
"text": "Correctly explains that hexagonal uses ports (interfaces) and adapters (implementations) with primary (driving) and secondary (driven) distinction"
},
{
"id": "11.2",
"text": "Correctly explains that clean architecture uses dependency rule (dependencies point inward) with entities/use-cases/adapters/frameworks layers"
},
{
"id": "11.3",
"text": "Recommends hexagonal for this specific case (multiple entry points: HTTP, gRPC, message consumer)"
},
{
"id": "11.4",
"text": "Mentions that both keep domain logic pure and free from infrastructure dependencies"
},
{
"id": "11.5",
"text": "Provides a directory structure example with adapter/primary/ and adapter/secondary/ or equivalent hexagonal layout"
}
]
},
{
"id": 12,
"name": "ddd-aggregate-root-mutations",
"description": "Tests whether the model enforces that all mutations go through the aggregate root in DDD",
"prompt": "I'm implementing DDD in Go for an e-commerce system. I have an Order aggregate with OrderItems. A user wants to add an item to an existing order. Show me how to structure this. The order should only be editable when in Draft status.",
"trap": "Without the skill, the model may allow direct mutation of OrderItems from outside the aggregate, or may not enforce the aggregate root pattern. The skill says all mutations go through the root.",
"assertions": [
{
"id": "12.1",
"text": "AddItem is a method on the Order aggregate root (not on OrderItem or a service)"
},
{
"id": "12.2",
"text": "Order fields (items, status) are unexported to prevent external mutation"
},
{
"id": "12.3",
"text": "AddItem validates the status constraint (only Draft orders are editable)"
},
{
"id": "12.4",
"text": "Repository interface is defined in the domain package, not in the infrastructure package"
},
{
"id": "12.5",
"text": "Domain types have no infrastructure imports (no sql, no http, no framework dependencies)"
}
]
},
{
"id": 13,
"name": "ddd-bounded-context-communication",
"description": "Tests whether the model uses anti-corruption layers or domain events between bounded contexts, not direct imports",
"prompt": "I have two bounded contexts in my Go DDD project: Order and Billing. When an order is placed, the billing context needs to create an invoice. How should these contexts communicate?",
"trap": "Without the skill, the model may suggest billing directly importing order's internal types. The skill says contexts communicate through domain events or anti-corruption layers, never by importing each other's internal types.",
"assertions": [
{
"id": "13.1",
"text": "Uses domain events (e.g. OrderPlaced event) for cross-context communication"
},
{
"id": "13.2",
"text": "Billing context does NOT directly import order's internal domain types"
},
{
"id": "13.3",
"text": "Shows or describes an anti-corruption layer that translates order events to billing-specific types"
},
{
"id": "13.4",
"text": "Each bounded context has its own domain, application, and adapter layers"
},
{
"id": "13.5",
"text": "Mentions that direct type imports between contexts create tight coupling"
}
]
},
{
"id": 14,
"name": "make-illegal-states-unrepresentable",
"description": "Tests whether the model uses types to enforce invariants rather than runtime validation",
"prompt": "I have a Go function that sends notifications. It accepts an email address as a string parameter. Sometimes callers pass invalid emails and we only catch it at send time. How can I prevent invalid emails from reaching the send function?",
"trap": "Without the skill, the model typically adds validation at the top of the send function. The skill says to make illegal states unrepresentable using types.",
"assertions": [
{
"id": "14.1",
"text": "Creates a dedicated Email type (struct with unexported address field)"
},
{
"id": "14.2",
"text": "Email can only be created via a constructor (NewEmail) that validates the address"
},
{
"id": "14.3",
"text": "The send function accepts the Email type instead of a raw string"
},
{
"id": "14.4",
"text": "Explains the principle: make illegal states unrepresentable through the type system"
},
{
"id": "14.5",
"text": "The unexported field prevents creating an Email without validation (cannot set address from outside the package)"
}
]
},
{
"id": 15,
"name": "fail-fast-validate-at-boundaries",
"description": "Tests whether the model validates at system boundaries and trusts data internally, rather than re-validating at every layer",
"prompt": "I'm building a Go web service with three layers: HTTP handler, service, and repository. Should I validate the request body (user_id, email, age) in all three layers to be safe?",
"trap": "Without the skill, the model may suggest defensive validation at every layer for 'safety'. The skill says validate at boundaries, trust internally -- don't re-validate the same data at every layer.",
"assertions": [
{
"id": "15.1",
"text": "Recommends validating at the HTTP handler layer (the system boundary)"
},
{
"id": "15.2",
"text": "Recommends that the service and repository layers trust the data is already valid"
},
{
"id": "15.3",
"text": "Explains WHY: re-validating at every layer clutters code and violates DRY"
},
{
"id": "15.4",
"text": "Does NOT suggest adding the same validation checks in all three layers"
},
{
"id": "15.5",
"text": "May distinguish between input validation (at boundary) and business rule validation (in domain)"
}
]
},
{
"id": 16,
"name": "explicit-over-implicit-defaults",
"description": "Tests whether the model favors explicit defaults in code over implicit magic (struct tags, reflection)",
"prompt": "I want to provide default values for my Go configuration struct. I'm thinking of using struct tags like `default:\"8080\"` with a reflection-based library. Is this a good approach in Go?",
"trap": "Without the skill, the model may endorse the struct-tag default approach as convenient. The skill says Go favors explicitness -- explicit defaults visible in code over implicit behavior hidden in struct tags and reflection.",
"assertions": [
{
"id": "16.1",
"text": "Recommends against using struct tags + reflection for defaults"
},
{
"id": "16.2",
"text": "Suggests explicit defaults in a constructor function (e.g. NewConfig())"
},
{
"id": "16.3",
"text": "Explains WHY: Go favors explicitness, struct tags hide behavior that readers cannot see without knowing the library"
},
{
"id": "16.4",
"text": "Shows a constructor that returns a Config with default values set explicitly"
}
]
},
{
"id": 17,
"name": "retry-context-check",
"description": "Tests whether retry logic checks context cancellation between attempts",
"prompt": "Write a Go retry function that retries a given operation up to 5 times with exponential backoff. The function should be production-ready.",
"trap": "Without the skill, the model may implement retry without checking ctx.Err() between attempts. The skill says retry logic MUST check context cancellation between attempts.",
"assertions": [
{ "id": "17.1", "text": "Function accepts a context.Context parameter" },
{
"id": "17.2",
"text": "Checks ctx.Err() or ctx.Done() between retry attempts"
},
{
"id": "17.3",
"text": "Uses select with ctx.Done() for the backoff delay (not time.Sleep)"
},
{ "id": "17.4", "text": "Implements exponential backoff" },
{
"id": "17.5",
"text": "Returns the context error if the context is cancelled during retry"
}
]
},
{
"id": 18,
"name": "ddd-value-object-money",
"description": "Tests whether the model implements money as a value object with cents (not float) and currency validation",
"prompt": "I'm implementing a pricing system in Go using DDD. I need to represent monetary amounts that support addition and comparison. Design the money type.",
"trap": "Without the skill, the model may use float64 for money (precision issues) or make it mutable. The skill shows Money as an immutable value object using int64 cents.",
"assertions": [
{
"id": "18.1",
"text": "Uses int64 (cents) not float64 for the amount -- avoids floating point precision issues"
},
{ "id": "18.2", "text": "Includes a currency field" },
{
"id": "18.3",
"text": "Fields are unexported (immutable value object, can only be created via constructor)"
},
{
"id": "18.4",
"text": "Add method validates currency match before addition"
},
{
"id": "18.5",
"text": "Constructor validates input (e.g. currency is required)"
}
]
}
]
# Architecture Patterns
## Table of Contents
- [Choose the Right Level of Architecture](#choose-the-right-level-of-architecture)
- [Keep Domain Pure](#keep-domain-pure)
- [Fail Fast — Validate at Boundaries](#fail-fast--validate-at-boundaries)
- [Make Illegal States Unrepresentable](#make-illegal-states-unrepresentable)
- [Detailed Architecture Guides](#detailed-architecture-guides)
- [12-Factor App Principles](#12-factor-app-principles)
- [Explicit Over Implicit](#explicit-over-implicit)
## Choose the Right Level of Architecture
Architecture complexity MUST match project scope — don't over-architect small projects. When starting a new project, ask the developer what architecture they prefer:
| Project Size | Recommended Approach |
| --- | --- |
| Script / small CLI (<500 lines) | Flat `main.go` + a few files, no layers |
| Medium service (500-5K lines) | Simple layered: `handler/`, `service/`, `repository/` |
| Large service / monolith (5K+ lines) | Clean architecture, hexagonal, or DDD — ask the team |
A 100-line CLI does not need a domain layer, ports and adapters, or dependency injection frameworks. Start simple and refactor when complexity demands it.
## Keep Domain Pure
Domain logic MUST remain pure — no framework or infrastructure dependencies. The domain layer contains business logic and types:
```go
// domain/order.go — pure business logic, no imports from infrastructure
package domain
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) AddItem(item Item) error {
if o.Status != StatusDraft {
return ErrOrderNotEditable
}
o.Items = append(o.Items, item)
return nil
}
```
Infrastructure concerns (database queries, HTTP clients, message queues) live in separate packages that depend on the domain — never the reverse.
## Fail Fast — Validate at Boundaries
Input MUST be validated at system boundaries (HTTP handlers, CLI argument parsing, message consumers). Once data enters your domain layer, trust it:
```go
// Handler layer — validate here
func (h *Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
var req CreateOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
if req.UserID == "" {
http.Error(w, "user_id is required", http.StatusBadRequest)
return
}
if len(req.Items) == 0 {
http.Error(w, "at least one item required", http.StatusBadRequest)
return
}
// Domain layer trusts this data is valid
order, err := h.service.CreateOrder(r.Context(), req.UserID, req.Items)
// ...
}
```
Don't re-validate the same data at every layer — it clutters the code and violates DRY.
## Make Illegal States Unrepresentable
Use Go's type system to prevent invalid states from being expressible in code:
```go
// Bad — status is a raw string, anything goes
type Order struct {
Status string // "pending"? "PENDING"? "active"? anything?
}
// Good — typed enum constrains the values
type OrderStatus int
const (
OrderStatusUnknown OrderStatus = iota // 0 = invalid
OrderStatusDraft // 1
OrderStatusConfirmed // 2
OrderStatusShipped // 3
)
type Order struct {
Status OrderStatus
}
```
```go
// Bad — email is a raw string, could be anything
func SendEmail(to string, body string) error { ... }
// Good — validated type enforces the constraint
type Email struct {
address string // unexported: can only be created via constructor
}
func NewEmail(raw string) (Email, error) {
if !isValidEmail(raw) {
return Email{}, fmt.Errorf("invalid email: %s", raw)
}
return Email{address: raw}, nil
}
```
## Detailed Architecture Guides
For projects that warrant a formal architecture (typically 5K+ lines), see the dedicated guides:
- [Domain-Driven Design (DDD)](./ddd.md) — aggregates, value objects, bounded contexts
- [Clean Architecture](./clean-architecture.md) — use cases, dependency rule, layered adapters
- [Hexagonal Architecture](./hexagonal-architecture.md) — ports, adapters, domain core isolation
## 12-Factor App Principles
→ See `samber/cc-skills-golang@golang-project-layout` for 12-Factor App conventions.
## Explicit Over Implicit
Go favors explicitness. Code should express its intent clearly without requiring the reader to know hidden conventions:
```go
// Bad — implicit behavior hidden in struct tags and reflection
type Config struct {
Port int `default:"8080"`
}
// Good — explicit defaults visible in code
func NewConfig() Config {
return Config{Port: 8080}
}
```
```go
// Bad — implicit dependency via global
func HandleRequest(w http.ResponseWriter, r *http.Request) {
user := globalDB.FindUser(r.Context(), userID) // where does globalDB come from?
}
// Good — explicit dependency via injection
func (h *Handler) HandleRequest(w http.ResponseWriter, r *http.Request) {
user := h.db.FindUser(r.Context(), userID) // clear: db is a field on Handler
}
```
→ See `samber/cc-skills-golang@golang-project-layout` skill for directory structure and layout patterns.
# Clean Architecture in Go
## Table of Contents
- [When to Use](#when-to-use)
- [The Dependency Rule](#the-dependency-rule)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Entity — pure domain logic, zero dependencies](#entity--pure-domain-logic-zero-dependencies)
- [Use Case — orchestrates business operations](#use-case--orchestrates-business-operations)
- [Adapter — implements a port](#adapter--implements-a-port)
- [Handler — translates HTTP to use case calls](#handler--translates-http-to-use-case-calls)
- [Key Principle](#key-principle)
- [Wiring](#wiring)
## When to Use
Apply clean architecture when you need strong separation between business logic and infrastructure — typically medium-to-large services (2K+ lines) where testability, framework independence, and clear dependency direction matter. Do NOT use for small CLI tools or scripts.
## The Dependency Rule
Dependencies point inward only. Inner layers never import outer layers.
```
Frameworks & Drivers → Interface Adapters → Use Cases → Entities
(HTTP, DB, gRPC) (handlers, repos) (app logic) (domain)
```
Each layer defines interfaces for what it needs. Outer layers implement those interfaces.
## Project Structure
```
order-service/
├── cmd/
│ └── server/
│ └── main.go # Wiring only — builds the dependency graph
├── internal/
│ ├── entity/
│ │ ├── order.go # Order entity + business rules
│ │ ├── item.go # OrderItem
│ │ └── status.go # OrderStatus enum
│ ├── order/
│ │ ├── place.go # PlaceOrderUseCase
│ │ ├── cancel.go # CancelOrderUseCase
│ │ └── port.go # Interfaces this use case depends on
│ ├── adapter/
│ │ ├── handler/
│ │ │ └── order_handler.go # HTTP handler — calls use cases
│ │ ├── repository/
│ │ │ └── order_postgres.go # OrderRepository — implements port
│ │ └── gateway/
│ │ └── payment_client.go # External payment API client
│ └── infrastructure/
│ ├── router.go # HTTP router setup
│ ├── database.go # DB connection
│ └── config.go # Config loading
├── go.mod
└── go.sum
```
## Code Examples
### Entity — pure domain logic, zero dependencies
```go
// internal/entity/order.go
package entity
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) Cancel() error {
if o.Status == StatusShipped {
return ErrCannotCancelShipped
}
o.Status = StatusCancelled
return nil
}
func (o *Order) Total() int64 {
var sum int64
for _, item := range o.Items {
sum += item.Price * int64(item.Quantity)
}
return sum
}
```
### Use Case — orchestrates business operations
```go
// internal/order/port.go
package order
// Ports — interfaces defined by the use case, implemented by adapters
type OrderRepository interface {
Save(ctx context.Context, order *entity.Order) error
FindByID(ctx context.Context, id string) (*entity.Order, error)
}
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount int64) error
}
```
```go
// internal/order/place.go
package order
type PlaceOrderUseCase struct {
orders OrderRepository
payments PaymentGateway
}
func NewPlaceOrderUseCase(orders OrderRepository, payments PaymentGateway) *PlaceOrderUseCase {
return &PlaceOrderUseCase{orders: orders, payments: payments}
}
func (uc *PlaceOrderUseCase) Execute(ctx context.Context, orderID string) error {
order, err := uc.orders.FindByID(ctx, orderID)
if err != nil {
return fmt.Errorf("finding order: %w", err)
}
if err := uc.payments.Charge(ctx, order.ID, order.Total()); err != nil {
return fmt.Errorf("charging payment: %w", err)
}
order.Status = entity.StatusPlaced
return uc.orders.Save(ctx, order)
}
```
### Adapter — implements a port
```go
// internal/adapter/repository/order_postgres.go
package repository
type OrderPostgres struct {
db *sql.DB
}
func NewOrderPostgres(db *sql.DB) *OrderPostgres {
return &OrderPostgres{db: db}
}
func (r *OrderPostgres) FindByID(ctx context.Context, id string) (*entity.Order, error) {
// SQL query, scan into entity.Order
}
func (r *OrderPostgres) Save(ctx context.Context, order *entity.Order) error {
// SQL upsert
}
```
### Handler — translates HTTP to use case calls
```go
// internal/adapter/handler/order_handler.go
package handler
type OrderHandler struct {
placeOrder *usecase.PlaceOrderUseCase
}
func (h *OrderHandler) HandlePlaceOrder(w http.ResponseWriter, r *http.Request) {
orderID := chi.URLParam(r, "id")
if err := h.placeOrder.Execute(r.Context(), orderID); err != nil {
// Map domain errors to HTTP status codes
http.Error(w, err.Error(), mapToHTTPStatus(err))
return
}
w.WriteHeader(http.StatusOK)
}
```
## Key Principle
Interfaces live where they are consumed, not where they are implemented. The `usecase/order/port.go` file defines `OrderRepository` — the adapter in `adapter/repository/` implements it. This keeps the use case layer free from infrastructure imports.
## Wiring
All dependency construction happens in `cmd/server/main.go`. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Data Handling Patterns
## Iterators for Large Data (Go 1.23+)
Process large datasets without allocating everything into memory:
```go
// Bad — loads all rows into memory
func AllUsers(db *sql.DB) ([]User, error) {
rows, err := db.Query("SELECT * FROM users")
// ... scan all into slice
}
// Good — iterator yields one at a time
func AllUsers(db *sql.DB) iter.Seq2[User, error] {
return func(yield func(User, error) bool) {
rows, err := db.Query("SELECT * FROM users")
if err != nil {
yield(User{}, err)
return
}
defer rows.Close()
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Name, &u.Email); err != nil {
yield(User{}, err)
return
}
if !yield(u, nil) {
return
}
}
}
}
```
## Streaming Large Transfers
When transferring large data between services (e.g., 1M rows from DB, 1M rows in HTTP response), use streaming patterns with iterators or `github.com/samber/ro` to prevent OOM:
```go
// Stream JSON array to HTTP response — constant memory
func (h *Handler) ExportUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("["))
first := true
for user, err := range h.repo.AllUsers(r.Context()) {
if err != nil {
slog.Error("streaming user", "error", err)
return
}
if !first {
w.Write([]byte(","))
}
json.NewEncoder(w).Encode(user)
first = false
}
w.Write([]byte("]"))
}
```
# Domain-Driven Design (DDD) in Go
## Table of Contents
- [When to Use](#when-to-use)
- [Building Blocks](#building-blocks)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Value Object — Money](#value-object--money)
- [Aggregate Root — Order](#aggregate-root--order)
- [Repository Interface — defined in domain](#repository-interface--defined-in-domain)
- [Application Service — orchestrates a use case](#application-service--orchestrates-a-use-case)
- [Bounded Contexts](#bounded-contexts)
- [Wiring](#wiring)
## When to Use
Apply DDD when the business domain is complex enough that the code structure should mirror the business model — typically services with 5K+ lines, multiple bounded contexts, or rich business rules. Do NOT use for simple CRUD apps or CLI tools.
## Building Blocks
| Concept | Go Mapping | Purpose |
| --- | --- | --- |
| **Entity** | Struct with identity field | Has unique ID, mutable state, lifecycle |
| **Value Object** | Immutable struct, compared by value | No identity — represents a measurement, quantity, or descriptor |
| **Aggregate** | Entity + child entities/value objects | Consistency boundary — all mutations go through the root |
| **Repository** | Interface in domain, impl in infrastructure | Persistence abstraction for aggregates |
| **Domain Service** | Function or struct in domain package | Logic that spans multiple aggregates |
| **Domain Event** | Struct describing a fact that happened | Decouples bounded contexts |
## Project Structure
Organize by **bounded context**, grouping domain, application, and adapters vertically. This scales across multiple contexts and clarifies ownership.
```
order-service/
├── cmd/
│ └── server/
│ └── main.go # Wiring only
├── internal/
│ ├── order/ # Bounded context: Order
│ │ ├── domain/
│ │ │ ├── order.go # Order aggregate root
│ │ │ ├── item.go # OrderItem entity
│ │ │ ├── status.go # OrderStatus enum
│ │ │ ├── repository.go # OrderRepository interface
│ │ │ └── events.go # OrderPlaced, OrderShipped events
│ │ ├── application/
│ │ │ ├── place_order.go # PlaceOrderHandler (command)
│ │ │ └── get_order.go # GetOrderHandler (query)
│ │ └── adapters/
│ │ ├── persistence/
│ │ │ └── postgres.go # OrderRepository implementation
│ │ └── http/
│ │ └── handler.go # HTTP transport
│ ├── billing/ # Bounded context: Billing (another example)
│ │ ├── domain/
│ │ ├── application/
│ │ └── adapters/
│ ├── shared/
│ │ └── money.go # Value object reused across contexts
│ └── events/
│ └── publisher.go # Shared event bus (infrastructure)
├── go.mod
└── go.sum
```
**Key principles:**
- Group each bounded context **vertically** (domain → application → adapters), not by technical role
- Use `adapters/` instead of `infrastructure/` to be explicit about Hexagonal Architecture
- Make cross-context boundaries explicit (see **Bounded Contexts** section below)
- Place shared infrastructure (event bus, logging) at `internal/{shared}/` or `internal/events/`
## Code Examples
### Value Object — Money
```go
// internal/domain/shared/money.go
package shared
type Money struct {
amount int64 // cents — avoids float precision issues
currency string
}
func NewMoney(amount int64, currency string) (Money, error) {
if currency == "" {
return Money{}, errors.New("currency is required")
}
return Money{amount: amount, currency: currency}, nil
}
func (m Money) Add(other Money) (Money, error) {
if m.currency != other.currency {
return Money{}, fmt.Errorf("cannot add %s to %s", other.currency, m.currency)
}
return Money{amount: m.amount + other.amount, currency: m.currency}, nil
}
```
### Aggregate Root — Order
```go
// internal/domain/order/order.go
package order
type Order struct {
id string
items []Item
status Status
total shared.Money
}
func NewOrder(id string) *Order {
return &Order{id: id, status: StatusDraft}
}
// All mutations go through the aggregate root
func (o *Order) AddItem(item Item) error {
if o.status != StatusDraft {
return ErrOrderNotEditable
}
o.items = append(o.items, item)
return o.recalculateTotal()
}
func (o *Order) Place() (OrderPlaced, error) {
if len(o.items) == 0 {
return OrderPlaced{}, ErrEmptyOrder
}
o.status = StatusPlaced
return OrderPlaced{OrderID: o.id, Total: o.total}, nil
}
```
### Repository Interface — defined in domain
```go
// internal/order/domain/repository.go
package domain
type Repository interface {
Save(ctx context.Context, order *Order) error
FindByID(ctx context.Context, id string) (*Order, error)
}
```
The implementation lives in `internal/order/adapters/persistence/postgres.go` and depends on the domain — never the reverse.
### Application Service — orchestrates a use case
```go
// internal/order/application/place_order.go
package application
import (
"context"
"fmt"
"myapp/internal/order/domain"
)
type PlaceOrderHandler struct {
orders domain.Repository
events EventPublisher
}
func (h *PlaceOrderHandler) Handle(ctx context.Context, cmd PlaceOrderCommand) error {
order, err := h.orders.FindByID(ctx, cmd.OrderID)
if err != nil {
return fmt.Errorf("finding order: %w", err)
}
evt, err := order.Place()
if err != nil {
return fmt.Errorf("placing order: %w", err)
}
if err := h.orders.Save(ctx, order); err != nil {
return fmt.Errorf("saving order: %w", err)
}
return h.events.Publish(ctx, evt)
}
```
## Bounded Contexts
Each bounded context maps to a top-level package under `internal/` with its own domain, application, and adapters. Contexts communicate through domain events or explicit anti-corruption layers — never by importing each other's internal types directly.
**Anti-corruption layer example:** If `billing/` needs to consume an `order.OrderPlaced` event, translate it to a billing-specific type:
```go
// internal/billing/adapters/events/order_events.go
package events
import (
"myapp/internal/events"
"myapp/internal/billing/domain"
)
type OrderPlacedSubscriber struct {
invoices domain.InvoiceRepository
}
// Receives order.OrderPlaced, translates to billing domain
func (s *OrderPlacedSubscriber) OnOrderPlaced(evt events.OrderPlaced) error {
// Translate and create invoice
return s.invoices.Create(evt.OrderID, evt.Total)
}
```
This prevents billing from depending on order's internal types.
For large systems, each context can be its own Go module in a workspace (`go.work`). See the `samber/cc-skills-golang@golang-project-layout` skill for workspace setup.
## Wiring
Wire dependencies in `cmd/server/main.go` using manual constructor injection. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Hexagonal Architecture (Ports & Adapters) in Go
## Table of Contents
- [When to Use](#when-to-use)
- [Core Concepts](#core-concepts)
- [Project Structure](#project-structure)
- [Code Examples](#code-examples)
- [Domain — pure business logic](#domain--pure-business-logic)
- [Ports — interfaces defined separately from implementations](#ports--interfaces-defined-separately-from-implementations)
- [Service — implements primary port, depends on secondary ports](#service--implements-primary-port-depends-on-secondary-ports)
- [Primary Adapter — HTTP handler calls the service port](#primary-adapter--http-handler-calls-the-service-port)
- [Secondary Adapter — implements a driven port](#secondary-adapter--implements-a-driven-port)
- [Multiple Entry Points](#multiple-entry-points)
- [Wiring](#wiring)
## When to Use
Apply hexagonal architecture when a service interacts with multiple external systems (databases, APIs, message queues, caches) and you want the domain logic fully decoupled from all of them. Particularly effective when the same business logic needs multiple entry points (HTTP, gRPC, CLI, message consumer). Do NOT use for simple CRUD apps or libraries.
## Core Concepts
- **Domain** — Business logic and types. No external dependencies.
- **Ports** — Interfaces that define how the domain interacts with the outside world.
- **Primary (driving) ports**: How the outside world calls into the domain (e.g., `OrderService` interface).
- **Secondary (driven) ports**: How the domain calls out to infrastructure (e.g., `OrderRepository`, `PaymentGateway` interfaces).
- **Adapters** — Concrete implementations of ports.
- **Primary adapters**: HTTP handlers, gRPC servers, CLI commands — they call primary ports.
- **Secondary adapters**: PostgreSQL repository, Stripe client, Redis cache — they implement secondary ports.
## Project Structure
```
order-service/
├── cmd/
│ ├── server/
│ │ └── main.go # HTTP server wiring
│ └── worker/
│ └── main.go # Message consumer wiring
├── internal/
│ ├── domain/
│ │ ├── order.go # Order entity + business rules
│ │ ├── item.go # OrderItem
│ │ └── status.go # OrderStatus enum
│ ├── port/
│ │ ├── incoming.go # Primary ports (OrderService interface)
│ │ └── outgoing.go # Secondary ports (OrderRepository, PaymentGateway)
│ ├── service/
│ │ └── order_service.go # Implements primary ports — orchestrates domain + secondary ports
│ └── adapter/
│ ├── primary/
│ │ ├── http/
│ │ │ ├── router.go
│ │ │ └── order_handler.go # HTTP adapter — calls OrderService
│ │ └── grpc/
│ │ └── order_server.go # gRPC adapter — calls OrderService
│ └── secondary/
│ ├── postgres/
│ │ └── order_repo.go # Implements OrderRepository
│ └── stripe/
│ └── payment.go # Implements PaymentGateway
├── go.mod
└── go.sum
```
## Code Examples
### Domain — pure business logic
```go
// internal/domain/order.go
package domain
type Order struct {
ID string
Items []Item
Status OrderStatus
}
func (o *Order) Ship() error {
if o.Status != StatusPaid {
return ErrOrderNotPaid
}
o.Status = StatusShipped
return nil
}
```
### Ports — interfaces defined separately from implementations
```go
// internal/port/incoming.go
package port
// Primary port — how the outside world drives the application
type OrderService interface {
PlaceOrder(ctx context.Context, items []domain.Item) (string, error)
ShipOrder(ctx context.Context, orderID string) error
GetOrder(ctx context.Context, orderID string) (*domain.Order, error)
}
```
```go
// internal/port/outgoing.go
package port
// Secondary ports — how the application reaches external systems
type OrderRepository interface {
Save(ctx context.Context, order *domain.Order) error
FindByID(ctx context.Context, id string) (*domain.Order, error)
}
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount int64) error
}
```
### Service — implements primary port, depends on secondary ports
```go
// internal/service/order_service.go
package service
type orderService struct {
orders port.OrderRepository
payments port.PaymentGateway
}
func NewOrderService(orders port.OrderRepository, payments port.PaymentGateway) port.OrderService {
return &orderService{orders: orders, payments: payments}
}
func (s *orderService) PlaceOrder(ctx context.Context, items []domain.Item) (string, error) {
order := domain.NewOrder(items)
if err := s.payments.Charge(ctx, order.ID, order.Total()); err != nil {
return "", fmt.Errorf("charging payment: %w", err)
}
if err := s.orders.Save(ctx, order); err != nil {
return "", fmt.Errorf("saving order: %w", err)
}
return order.ID, nil
}
```
### Primary Adapter — HTTP handler calls the service port
```go
// internal/adapter/primary/http/order_handler.go
package http
type OrderHandler struct {
svc port.OrderService
}
func NewOrderHandler(svc port.OrderService) *OrderHandler {
return &OrderHandler{svc: svc}
}
func (h *OrderHandler) HandlePlaceOrder(w http.ResponseWriter, r *http.Request) {
var req PlaceOrderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
id, err := h.svc.PlaceOrder(r.Context(), req.Items)
if err != nil {
http.Error(w, err.Error(), mapToHTTPStatus(err))
return
}
json.NewEncoder(w).Encode(map[string]string{"id": id})
}
```
### Secondary Adapter — implements a driven port
```go
// internal/adapter/secondary/postgres/order_repo.go
package postgres
type OrderRepo struct {
db *sql.DB
}
func NewOrderRepo(db *sql.DB) *OrderRepo {
return &OrderRepo{db: db}
}
func (r *OrderRepo) Save(ctx context.Context, order *domain.Order) error {
// SQL upsert
}
func (r *OrderRepo) FindByID(ctx context.Context, id string) (*domain.Order, error) {
// SQL query
}
```
## Multiple Entry Points
The hexagonal approach shines when the same `OrderService` is called from different primary adapters — HTTP for external clients, gRPC for internal services, a message consumer for async events. Each adapter is wired in its own `cmd/` entry point.
## Wiring
Construct adapters and inject them in `cmd/server/main.go`. → See `samber/cc-skills-golang@golang-dependency-injection` skill for DI library alternatives.
# Resource Management Patterns
## Table of Contents
- [Defer Close Immediately](#defer-close-immediately)
- [`runtime.AddCleanup` over `runtime.SetFinalizer`](#runtimeaddcleanup-over-runtimesetfinalizer)
- [Resource Pools](#resource-pools)
- [Graceful Shutdown](#graceful-shutdown)
## Defer Close Immediately
`defer Close()` MUST be called immediately after opening — NEVER delay. This prevents leaks when code is modified later and new return paths are added:
```go
// Good — defer is right next to open
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
// Bad — Close() is far from Open(), easy to forget when adding early returns
f, err := os.Open(path)
if err != nil {
return err
}
// ... 50 lines of code ...
f.Close() // might never run if a new return is added above
```
This applies to all closeable resources: files, SQL rows, HTTP response bodies, gzip readers, bufio scanners wrapping readers, etc.
```go
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
rows, err := db.QueryContext(ctx, query)
if err != nil {
return err
}
defer rows.Close()
```
## `runtime.AddCleanup` over `runtime.SetFinalizer`
`runtime.AddCleanup` SHOULD be preferred over `runtime.SetFinalizer` (Go 1.24+):
```go
type Resource struct {
handle uintptr
}
func NewResource() *Resource {
r := &Resource{handle: acquireHandle()}
runtime.AddCleanup(r, func(handle uintptr) {
releaseHandle(handle)
}, r.handle)
return r
}
```
`AddCleanup` is preferred because:
- Multiple cleanups can be attached to the same object
- The cleanup function receives a copy of the value, not the object itself — no resurrection risk
- Cleanups run even if the object is part of a cycle
## Resource Pools
Resource pools SHOULD use channels with a fixed capacity for bounded allocation. Use channel-based pools or `sync.Pool` to manage limited resources between consumers. Always set a maximum size:
```go
type ConnPool struct {
conns chan *Conn
}
func NewConnPool(maxSize int, factory func() (*Conn, error)) (*ConnPool, error) {
pool := &ConnPool{
conns: make(chan *Conn, maxSize),
}
// Pre-fill with initial connections
for range maxSize {
conn, err := factory()
if err != nil {
return nil, fmt.Errorf("creating connection: %w", err)
}
pool.conns <- conn
}
return pool, nil
}
func (p *ConnPool) Get(ctx context.Context) (*Conn, error) {
select {
case conn := <-p.conns:
return conn, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (p *ConnPool) Put(conn *Conn) {
select {
case p.conns <- conn:
default:
conn.Close() // pool is full, discard
}
}
```
## Graceful Shutdown
Graceful shutdown MUST use `signal.NotifyContext` for clean termination. All resources (connections, files, channels) MUST be drained before process exit. Use `os/signal` and context cancellation:
```go
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
syscall.SIGINT, syscall.SIGTERM,
)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: router}
// Start server in background
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server error", "error", err)
}
}()
slog.Info("server started", "addr", ":8080")
// Wait for interrupt signal
<-ctx.Done()
slog.Info("shutting down...")
// Give outstanding requests time to complete
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "error", err)
}
// Close other resources: database connections, message queues, etc.
db.Close()
slog.Info("shutdown complete")
}
```
This pattern applies to any long-running service — gRPC servers, message consumers, background workers. The key elements are:
1. Capture OS signals with `signal.NotifyContext`
2. Start the server in a goroutine
3. Block on context cancellation
4. Shut down with a timeout to drain in-flight requests
5. Close all remaining resources in order
For goroutine shutdown patterns, see the `samber/cc-skills-golang@golang-concurrency` skill.
...@@ -2,12 +2,85 @@ ...@@ -2,12 +2,85 @@
Sincroniza estudiantes (con padres y planes de pago) desde PostgreSQL hacia MongoDB mediante sondeo completo cada N minutos. Sincroniza estudiantes (con padres y planes de pago) desde PostgreSQL hacia MongoDB mediante sondeo completo cada N minutos.
## Ejecución rápida
```bash
go run ./cmd/server
```
El proceso lee el `.env` del directorio raíz, levanta Postgres/Mongo, arranca un scheduler por pipeline y expone la API en `PORT` (8080 por defecto). Los pipelines no corren al arrancar: el primer ciclo ocurre según el horario configurado.
Disparar un pipeline a mano y consultar su estado:
```bash
curl -s -X POST localhost:8080/api/v1/sync/students/trigger
curl -s localhost:8080/api/v1/sync/students/status
```
Verificar conectividad antes de sincronizar:
```bash
curl -s localhost:8080/api/v1/health
```
### Pipelines
| Pipeline | Colección Mongo | `IDField` | Docs esperados | Ciclo medido |
|---|---|---|---|---|
| `students` | `students` | `student_id` | ~36 mil | segundos |
| `payment_plans` | `payment_plans` | `payment_plan_id` | cientos de miles | segundos |
| `parents` | `parents` | `parent_id` | decenas de miles | segundos |
| `users` | `users` | `user_id` | miles | segundos |
| `professors` | `professors` | `professor_id` | miles | segundos |
| `attendance` | `c_attendance` | `attendance_id` | **~321 mil** | **~56 min** (estimado) |
Los tiempos de los cinco pipelines chicos son de segundos; el de `attendance` es una extrapolación (lectura medida completa + upsert medido sobre 20 mil documentos), porque el ciclo completo no llega a terminar — ver la advertencia más abajo.
Cada pipeline se dispara y se consulta reemplazando el nombre en la ruta: `/api/v1/sync/<pipeline>/trigger` y `/api/v1/sync/<pipeline>/status`. Los endpoints se registran solos a partir de `config.Pipelines`.
El `trigger` es **síncrono**: la respuesta no vuelve hasta que el ciclo termina. Para pipelines grandes (>1 min) conviene dispararlo en segundo plano:
```bash
curl -s -X POST localhost:8080/api/v1/sync/attendance/trigger > /tmp/attendance.log &
curl -s localhost:8080/api/v1/sync/attendance/status
```
### Antes del primer ciclo
- Cada colección necesita **índice único** sobre su `IDField` (`student_id`, `attendance_id`, etc.); el código no lo crea. Sin él `BulkUpsert` matchea un documento arbitrario entre los duplicados, y `MoveToDeleted` archiva y borra solo uno por ciclo, así que los duplicados se acumulan en la colección viva.
- La tabla `sync_state` se crea sola al arrancar, con una fila por `StateID` (1–6). Si agregás un pipeline con un `StateID` nuevo, agregá también el `VALUES (...)` del seed en `internal/infrastructure/database/postgres/client.go`, o el arranque falla al leer el estado.
- `attendance` exige además un índice sobre `ac_asistencia(matricula_id, asistencia_fecha)`.
### ⚠️ `attendance` no entra en el timeout del scheduler
`internal/usecase/scheduler.go` impone un timeout duro de **4 minutos por ciclo**. Medido contra el entorno real, el ciclo de `attendance` tarda **~56 minutos**:
| fase | tiempo |
|---|---|
| lectura de Postgres a memoria | 2m05s (1.5 GB de heap, 321 mil documentos) |
| hashing `row_hash` | ~4s |
| `BulkUpsert` a Mongo remoto | **~54 min** (~100 docs/s) |
Con el contexto cancelado a los 4 min el `BulkWrite` se aborta a medias y `sync_state` nunca avanza, así que el ciclo **nunca completa**. Mientras tanto el `/status` va a mostrar el `last_error`.
Opciones, de menor a mayor effort:
1. Subir `cycleTimeout` en `internal/usecase/scheduler.go` (afecta a todos los pipelines) o hacerlo configurable por pipeline vía env.
2. Procesar en lotes de N matrículas por ciclo en vez de los 321 mil de una vez.
3. Reducir el alcance del documento a un solo mes en vez de todo el año.
No pongas `attendance` en `MODE=daily` hasta resolver esto.
### Horarios
Cada pipeline tiene su propio horario vía `SYNC_<NOMBRE>_{MODE,TIME,INTERVAL}` (ver Configuración más abajo). El scheduler corre un ciclo por pipeline en paralelo, no en serie: los cinco pipelines chicos conviven sin problema, pero `attendance` monopoliza la conexión de Mongo durante toda su hora de escritura.
## Configuración ## Configuración
1. La tabla `sync_state` se crea/inicializa automáticamente al arrancar (fila `id=1` estudiantes) — no se requiere paso de migración manual (`migrations/0001_create_sync_state.sql` se conserva como referencia). 1. La tabla `sync_state` se crea/inicializa automáticamente al arrancar, con una fila por pipeline (`id` 1 a 6: students, payment_plans, parents, users, professors, attendance) — no se requiere paso de migración manual (`migrations/0001_create_sync_state.sql` se conserva como referencia). El seed está en `internal/infrastructure/database/postgres/client.go`: si agregás un pipeline con `StateID` nuevo, agregá el `VALUES (...)` ahí o el arranque falla con `no rows in result set`.
2. Asegúrate de que la colección `students` exista en Mongo con el validador `$jsonSchema` provisto (requeridos: `student_id` int, `enrollment_id` int). La colección `deleted_students` archiva los estudiantes eliminados en el origen — no requiere configuración de esquema. 2. Asegúrate de que la colección `students` exista en Mongo con el validador `$jsonSchema` provisto (requeridos: `student_id` int, `enrollment_id` int). La colección `deleted_students` archiva los estudiantes eliminados en el origen — no requiere configuración de esquema.
3. Define las variables de entorno: `PG_DSN`, `MONGO_URI`, `MONGO_DB=intranet` (o tu base de datos), `SYNC_INTERVAL` (por defecto `5m`), `PORT` (por defecto `8080`). Los nombres de función PG / colección Mongo por pipeline ya no son variables de entorno — se definen en `internal/infrastructure/config/pipelines.go`. Agrega un nuevo pipeline añadiendo una entrada ahí, no variables de entorno. 3. Define las variables de entorno: `PG_DSN`, `MONGO_URI`, `MONGO_DB=intranet` (o tu base de datos), `SYNC_INTERVAL` (por defecto `5m`), `PORT` (por defecto `8080`). Los nombres de función PG / colección Mongo por pipeline ya no son variables de entorno — se definen en `internal/infrastructure/config/pipelines.go`. Agrega un nuevo pipeline añadiendo una entrada ahí, no variables de entorno.
4. Horario por pipeline (opcional, `SYNC_<NOMBRE>_...` en mayúsculas, ej. `SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`): 4. Horario por pipeline (opcional, `SYNC_<NOMBRE>_...` en mayúsculas, ej. `SYNC_STUDENTS_MODE`, `SYNC_PAYMENT_PLANS_MODE`, `SYNC_PARENTS_MODE`, `SYNC_USERS_MODE`, `SYNC_PROFESSORS_MODE`, `SYNC_ATTENDANCE_MODE`):
- `SYNC_<NOMBRE>_MODE`: `interval` (por defecto) o `daily`. - `SYNC_<NOMBRE>_MODE`: `interval` (por defecto) o `daily`.
- `SYNC_<NOMBRE>_INTERVAL`: duración tipo `5m`/`1h` (modo `interval`; si falta, usa `SYNC_INTERVAL`). - `SYNC_<NOMBRE>_INTERVAL`: duración tipo `5m`/`1h` (modo `interval`; si falta, usa `SYNC_INTERVAL`).
- `SYNC_<NOMBRE>_TIME`: hora `HH:MM` (modo `daily`, obligatoria en ese modo). Ej: `SYNC_STUDENTS_MODE=daily` + `SYNC_STUDENTS_TIME=03:00` corre estudiantes una vez al día a las 3am. - `SYNC_<NOMBRE>_TIME`: hora `HH:MM` (modo `daily`, obligatoria en ese modo). Ej: `SYNC_STUDENTS_MODE=daily` + `SYNC_STUDENTS_TIME=03:00` corre estudiantes una vez al día a las 3am.
...@@ -22,6 +95,8 @@ Todos los endpoints llevan el prefijo `/api/v1`. ...@@ -22,6 +95,8 @@ Todos los endpoints llevan el prefijo `/api/v1`.
- `POST /api/v1/sync/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — pipeline de planes de pago (misma forma). - `POST /api/v1/sync/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — pipeline de planes de pago (misma forma).
- `POST /api/v1/sync/parents/trigger` / `GET /api/v1/sync/parents/status` — pipeline de padres/apoderados (misma forma). - `POST /api/v1/sync/parents/trigger` / `GET /api/v1/sync/parents/status` — pipeline de padres/apoderados (misma forma).
- `POST /api/v1/sync/users/trigger` / `GET /api/v1/sync/users/status` — pipeline de usuarios (misma forma). - `POST /api/v1/sync/users/trigger` / `GET /api/v1/sync/users/status` — pipeline de usuarios (misma forma).
- `POST /api/v1/sync/professors/trigger` / `GET /api/v1/sync/professors/status` — pipeline de profesores (misma forma).
- `POST /api/v1/sync/attendance/trigger` / `GET /api/v1/sync/attendance/status` — pipeline de asistencia (misma forma, pero ver la advertencia de timeout arriba).
## Estructura del proyecto (arquitectura limpia) ## Estructura del proyecto (arquitectura limpia)
...@@ -58,6 +133,27 @@ Padres/apoderados: une `persona.pe_persona` con una subconsulta agregada sobre ` ...@@ -58,6 +133,27 @@ Padres/apoderados: une `persona.pe_persona` con una subconsulta agregada sobre `
Usuarios: una fila por login (`user_id`, `user_login`, `user_password`, `user_creation_date`, `parent_id`, `user_status`). Upsert por `user_id`. Usuarios: una fila por login (`user_id`, `user_login`, `user_password`, `user_creation_date`, `parent_id`, `user_status`). Upsert por `user_id`.
Asistencia: `configuracion.co_calendario` cruzado con los alumnos del ciclo 28 / periodo 14 (`ac_aula`), con `LEFT JOIN` a `academico.ac_asistencia` por `(matricula_id, asistencia_fecha)`. El origen devuelve **una fila por alumno y día**; el reader las agrupa en **un documento por alumno y mes** (`registros` con un item por día del calendario). Upsert por `attendance_id`.
Dos detalles que no son obvios en el origen:
- `ac_asistencia` tiene más de una fila para el mismo `(matricula_id, asistencia_fecha)` (189 pares solo en el ciclo 28). El CTE `asistencia_dia` deduplica con `DISTINCT ON` quedándose con la fila de `fecha_hora_registro` más reciente; sin eso `registros` repetiría días y el `row_hash` nunca convergería.
- El origen **no trae `attendance_id`**. Se compone en el reader como `matricula_id * 100 + mes` (`postgres.BuildAttendanceID`), porque un alumno tiene un documento por mes.
El query está acotado a `calendario_fecha <= CURRENT_DATE` sobre el año en curso, así que el mes en curso queda parcial y, el 1 de enero, la reconciliación de borrados archiva los documentos del año anterior a `deleted_c_attendance`.
Semántica de `resumen_mes` (`postgres.summarize`):
| campo | significado |
|---|---|
| `dias_calendario` | días del mes presentes en `co_calendario` |
| `feriados` | de esos, los marcados como feriado |
| `dias_habiles` | días **con registro** de asistencia |
| `presentes` / `tardanzas` / `faltas` | días con registro de ese tipo |
| `faltas_justificadas` | faltas con `justifico = true` |
Un día hábil sin registro no cuenta como falta, porque el origen no lo reporta.
## Comportamiento de sincronización ## Comportamiento de sincronización
Cada ciclo tiene dos fases: Cada ciclo tiene dos fases:
......
package entities
import "time"
// AttendanceRecord es un día suelto del calendario del alumno. Los días sin registro de
// asistencia llegan igual, con Type vacío y AttendanceID nil.
type AttendanceRecord struct {
AttendanceID *int `bson:"asistencia_id" json:"asistencia_id"`
Date string `bson:"fecha" json:"fecha"`
Holiday bool `bson:"es_feriado" json:"es_feriado"`
EntryTime *string `bson:"hora_ingreso" json:"hora_ingreso"`
Type string `bson:"tipo" json:"tipo"`
Justified bool `bson:"justificado" json:"justificado"`
JustificationCause *string `bson:"motivo_justificacion" json:"motivo_justificacion"`
}
// AttendanceSummary agrega los contadores del mes del alumno.
type AttendanceSummary struct {
CalendarDays int `bson:"dias_calendario" json:"dias_calendario"`
WorkingDays int `bson:"dias_habiles" json:"dias_habiles"`
Holidays int `bson:"feriados" json:"feriados"`
Present int `bson:"presentes" json:"presentes"`
Late int `bson:"tardanzas" json:"tardanzas"`
Absences int `bson:"faltas" json:"faltas"`
JustifiedAbsences int `bson:"faltas_justificadas" json:"faltas_justificadas"`
}
// Attendance es un documento por alumno por mes: el id de negocio se compone de la
// matrícula y el mes (attendance_id), no de una columna del origen.
type Attendance struct {
AttendanceID int `bson:"attendance_id" json:"attendance_id"`
StudentID int `bson:"estudiante_id" json:"estudiante_id"`
EnrollmentID int `bson:"matricula_id" json:"matricula_id"`
CycleID int `bson:"ciclo_id" json:"ciclo_id"`
AcademicPeriodID int `bson:"periodo_academico_id" json:"periodo_academico_id"`
Month int `bson:"mes" json:"mes"`
MonthDescription string `bson:"mes_descripcion" json:"mes_descripcion"`
Records []AttendanceRecord `bson:"registros" json:"registros"`
MonthSummary AttendanceSummary `bson:"resumen_mes" json:"resumen_mes"`
CreatedAt time.Time `bson:"created_at" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
RowHash string `bson:"row_hash,omitempty" json:"-"`
}
func (r *Attendance) SetUpdatedAt(t time.Time) {
r.UpdatedAt = t
}
func (r *Attendance) SetRowHash(h string) {
r.RowHash = h
}
func (r *Attendance) SetCreatedAt(t time.Time) {
r.CreatedAt = t
}
...@@ -54,4 +54,12 @@ var Pipelines = []PipelineDef{ ...@@ -54,4 +54,12 @@ var Pipelines = []PipelineDef{
IDField: "professor_id", IDField: "professor_id",
StateID: 5, StateID: 5,
}, },
{
Name: "attendance",
PGQuery: sql.AttendanceQuery,
MongoCollection: "c_attendance",
MongoDeletedCollection: "deleted_c_attendance",
IDField: "attendance_id",
StateID: 6,
},
} }
package postgres
import (
"context"
"fmt"
"sort"
"time"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
const dateLayout = "2006-01-02"
var monthDescriptions = [...]string{
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
"Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre",
}
// BuildAttendanceID compone el id de negocio del documento: matrícula * 100 + mes.
// El origen no trae esta columna, se deriva acá porque un alumno tiene un documento por mes.
func BuildAttendanceID(enrollmentID, month int) int {
return enrollmentID*100 + month
}
func monthDescription(month int) string {
if month < 1 || month > len(monthDescriptions) {
return ""
}
return monthDescriptions[month-1]
}
type AttendanceReader struct {
pool *Pool
query string
}
func NewAttendanceReader(pool *Pool, query string) repositories.SourceReader {
return &AttendanceReader{pool: pool, query: query}
}
func (r *AttendanceReader) FetchAll(ctx context.Context) ([]entities.SyncRow, error) {
rows, err := r.pool.Pool.Query(ctx, r.query)
if err != nil {
return nil, fmt.Errorf("query attendance: %w", err)
}
defer rows.Close()
docs := make(map[int]*entities.Attendance)
for rows.Next() {
var (
enrollmentID int
studentID int
cycleID int
academicPeriodID int
month int
date time.Time
isHoliday bool
recordID *int
entryTime *string
attendanceType string
justified bool
justificationText *string
)
if err := rows.Scan(
&enrollmentID,
&studentID,
&cycleID,
&academicPeriodID,
&month,
&date,
&isHoliday,
&recordID,
&entryTime,
&attendanceType,
&justified,
&justificationText,
); err != nil {
return nil, fmt.Errorf("scan attendance row: %w", err)
}
attendanceID := BuildAttendanceID(enrollmentID, month)
doc, ok := docs[attendanceID]
if !ok {
doc = &entities.Attendance{
AttendanceID: attendanceID,
StudentID: studentID,
EnrollmentID: enrollmentID,
CycleID: cycleID,
AcademicPeriodID: academicPeriodID,
Month: month,
MonthDescription: monthDescription(month),
Records: make([]entities.AttendanceRecord, 0, daysInMonth(date)),
}
docs[attendanceID] = doc
}
doc.Records = append(doc.Records, entities.AttendanceRecord{
AttendanceID: recordID,
Date: date.Format(dateLayout),
Holiday: isHoliday,
EntryTime: entryTime,
Type: attendanceType,
Justified: justified,
JustificationCause: justificationText,
})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate attendance rows: %w", err)
}
attendanceIDs := make([]int, 0, len(docs))
for id := range docs {
attendanceIDs = append(attendanceIDs, id)
}
sort.Ints(attendanceIDs)
result := make([]entities.SyncRow, 0, len(docs))
for _, id := range attendanceIDs {
doc := docs[id]
sort.SliceStable(doc.Records, func(i, j int) bool {
return doc.Records[i].Date < doc.Records[j].Date
})
doc.MonthSummary = summarize(doc.Records)
result = append(result, entities.SyncRow{ID: id, Doc: doc})
}
return result, nil
}
// summarize cuenta sobre los días del mes: dias_calendario son todos los del calendario,
// feriados los marcados como tal, y dias_habiles los que tienen registro de asistencia.
// Un día hábil sin registro no cuenta como falta, porque el origen no lo reporta.
func summarize(records []entities.AttendanceRecord) entities.AttendanceSummary {
summary := entities.AttendanceSummary{CalendarDays: len(records)}
for _, rec := range records {
if rec.Holiday {
summary.Holidays++
}
if rec.AttendanceID == nil {
continue
}
summary.WorkingDays++
switch rec.Type {
case "asistencia":
summary.Present++
case "tardanza":
summary.Late++
case "falta":
summary.Absences++
if rec.Justified {
summary.JustifiedAbsences++
}
}
}
return summary
}
func daysInMonth(date time.Time) int {
return time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location()).AddDate(0, 1, -1).Day()
}
...@@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS sync_state ( ...@@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS sync_state (
); );
INSERT INTO sync_state (id, last_synced_at) INSERT INTO sync_state (id, last_synced_at)
VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z') VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z'), (6, '1970-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING; ON CONFLICT (id) DO NOTHING;
` `
......
package sql
// AttendanceQuery devuelve una fila por alumno y por día del calendario del año en curso
// (hasta hoy), con la asistencia del día si existe. El lector agrupa esas filas en un
// documento por alumno y mes (attendance_id = matricula_id * 100 + mes).
//
// ac_asistencia tiene más de una fila para el mismo (matricula_id, asistencia_fecha), así que
// asistencia_dia se deduplica con DISTINCT ON quedándose con la fila más reciente; sin eso el
// cross join devolvería días repetidos y el array registros dejaría de tener un item por día.
const AttendanceQuery = `
WITH asistencia_dia AS (SELECT DISTINCT ON (a.matricula_id, a.asistencia_fecha)
a.matricula_id,
a.asistencia_fecha,
a.asistencia_id,
a.hora_ingreso,
a.tipo_asistencia_id,
COALESCE(a.justifico, false) as justifico,
a.justifico_observacion
FROM academico.ac_asistencia a
INNER JOIN matricula.ma_matricula m ON m.matricula_id = a.matricula_id
INNER JOIN academico.ac_aula au ON au.aula_id = m.aula_id_asiste
WHERE NOT m.matricula_retirado
AND NOT m.matricula_anulada
AND au.periodo_academico_id = 14
AND au.ciclo_id = 28
AND EXTRACT('YEAR' FROM a.asistencia_fecha) = EXTRACT('YEAR' FROM CURRENT_DATE)
AND a.asistencia_fecha <= CURRENT_DATE
ORDER BY a.matricula_id, a.asistencia_fecha,
a.fecha_hora_registro DESC NULLS LAST, a.asistencia_id DESC
), calendario AS (SELECT C.calendario_fecha as fecha,
C.calendario_es_feriado as es_feriado
FROM configuracion.co_calendario C
WHERE EXTRACT('YEAR' FROM C.calendario_fecha) = EXTRACT('YEAR' FROM CURRENT_DATE)
AND C.calendario_fecha <= CURRENT_DATE
), alumno AS (SELECT M.matricula_id,
e.estudiante_id,
au.ciclo_id,
au.periodo_academico_id
FROM matricula.ma_matricula M
INNER JOIN matricula.ma_estudiante e ON e.estudiante_id = M.estudiante_id
INNER JOIN persona.pe_persona P ON P.persona_id = e.persona_id
INNER JOIN academico.ac_aula au ON au.aula_id = M.aula_id_asiste
WHERE NOT M.matricula_retirado
AND NOT M.matricula_anulada
AND au.periodo_academico_id = 14
AND au.ciclo_id = 28
)
SELECT alumno.matricula_id as enrollment_id,
alumno.estudiante_id as student_id,
alumno.ciclo_id as cycle_id,
alumno.periodo_academico_id as academic_period_id,
EXTRACT('MONTH' FROM calendario.fecha) as attendance_month,
calendario.fecha as attendance_date,
calendario.es_feriado as is_holiday,
A.asistencia_id as attendance_row_id,
A.hora_ingreso as entry_time,
CASE A.tipo_asistencia_id
WHEN 1 THEN 'asistencia'
WHEN 2 THEN 'tardanza'
WHEN 3 THEN 'falta'
WHEN 4 THEN 'no_corresponde'
ELSE ''
END as attendance_type,
COALESCE(A.justifico, false) as justified,
A.justifico_observacion as justification_cause
FROM alumno
CROSS JOIN calendario
LEFT JOIN asistencia_dia A
ON A.matricula_id = alumno.matricula_id
AND A.asistencia_fecha = calendario.fecha
ORDER BY alumno.matricula_id, EXTRACT('MONTH' FROM calendario.fecha), calendario.fecha;
`
...@@ -26,6 +26,8 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou ...@@ -26,6 +26,8 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou
return postgres.NewUserReader(pool, query), nil return postgres.NewUserReader(pool, query), nil
case "professors": case "professors":
return postgres.NewProfessorReader(pool, query), nil return postgres.NewProfessorReader(pool, query), nil
case "attendance":
return postgres.NewAttendanceReader(pool, query), nil
default: default:
return nil, fmt.Errorf("no reader wired for pipeline %q", name) return nil, fmt.Errorf("no reader wired for pipeline %q", name)
} }
......
{
"version": 1,
"skills": {
"golang-concurrency": {
"source": "samber/cc-skills-golang",
"sourceType": "github",
"skillPath": "skills/golang-concurrency/SKILL.md",
"computedHash": "f76a7af92805c94c91b7aea0f743e20c4613ca346203cbd7f0e9d296a7970385"
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment