@zimezone/z-command 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/package.json +4 -1
  2. package/templates/agents/api-documenter.agent.md +161 -0
  3. package/templates/agents/architect-review.agent.md +146 -0
  4. package/templates/agents/arm-cortex-expert.agent.md +288 -0
  5. package/templates/agents/backend-architect.agent.md +309 -0
  6. package/templates/agents/backend-security-coder.agent.md +152 -0
  7. package/templates/agents/bash-pro.agent.md +285 -0
  8. package/templates/agents/c-pro.agent.md +35 -0
  9. package/templates/agents/c4-code.agent.md +320 -0
  10. package/templates/agents/c4-component.agent.md +227 -0
  11. package/templates/agents/c4-container.agent.md +248 -0
  12. package/templates/agents/c4-context.agent.md +235 -0
  13. package/templates/agents/conductor-validator.agent.md +245 -0
  14. package/templates/agents/csharp-pro.agent.md +38 -0
  15. package/templates/agents/customer-support.agent.md +148 -0
  16. package/templates/agents/database-admin.agent.md +142 -0
  17. package/templates/agents/database-architect.agent.md +238 -0
  18. package/templates/agents/database-optimizer.agent.md +144 -0
  19. package/templates/agents/debugger.agent.md +30 -0
  20. package/templates/agents/deployment-engineer.agent.md +0 -0
  21. package/templates/agents/devops-troubleshooter.agent.md +138 -0
  22. package/templates/agents/django-pro.agent.md +159 -0
  23. package/templates/agents/docs-architect.agent.md +77 -0
  24. package/templates/agents/dotnet-architect.agent.md +175 -0
  25. package/templates/agents/dx-optimizer.agent.md +63 -0
  26. package/templates/agents/elixir-pro.agent.md +38 -0
  27. package/templates/agents/error-detective.agent.md +32 -0
  28. package/templates/agents/event-sourcing-architect.agent.md +42 -0
  29. package/templates/agents/fastapi-pro.agent.md +171 -0
  30. package/templates/agents/firmware-analyst.agent.md +330 -0
  31. package/templates/agents/frontend-security-coder.agent.md +149 -0
  32. package/templates/agents/haskell-pro.agent.md +37 -0
  33. package/templates/agents/hr-pro.agent.md +105 -0
  34. package/templates/agents/incident-responder.agent.md +190 -0
  35. package/templates/agents/ios-developer.agent.md +198 -0
  36. package/templates/agents/java-pro.agent.md +156 -0
  37. package/templates/agents/javascript-pro.agent.md +35 -0
  38. package/templates/agents/julia-pro.agent.md +187 -0
  39. package/templates/agents/legal-advisor.agent.md +49 -0
  40. package/templates/agents/malware-analyst.agent.md +272 -0
  41. package/templates/agents/mermaid-expert.agent.md +39 -0
  42. package/templates/agents/minecraft-bukkit-pro.agent.md +104 -0
  43. package/templates/agents/mobile-security-coder.agent.md +163 -0
  44. package/templates/agents/monorepo-architect.agent.md +44 -0
  45. package/templates/agents/observability-engineer.agent.md +228 -0
  46. package/templates/agents/performance-engineer.agent.md +167 -0
  47. package/templates/agents/php-pro.agent.md +43 -0
  48. package/templates/agents/posix-shell-pro.agent.md +284 -0
  49. package/templates/agents/quant-analyst.agent.md +32 -0
  50. package/templates/agents/reference-builder.agent.md +167 -0
  51. package/templates/agents/reverse-engineer.agent.md +202 -0
  52. package/templates/agents/risk-manager.agent.md +41 -0
  53. package/templates/agents/ruby-pro.agent.md +35 -0
  54. package/templates/agents/rust-pro.agent.md +156 -0
  55. package/templates/agents/sales-automator.agent.md +35 -0
  56. package/templates/agents/scala-pro.agent.md +60 -0
  57. package/templates/agents/search-specialist.agent.md +59 -0
  58. package/templates/agents/security-auditor.agent.md +138 -0
  59. package/templates/agents/seo-authority-builder.agent.md +116 -0
  60. package/templates/agents/seo-cannibalization-detector.agent.md +103 -0
  61. package/templates/agents/seo-content-auditor.agent.md +63 -0
  62. package/templates/agents/seo-content-planner.agent.md +88 -0
  63. package/templates/agents/seo-content-refresher.agent.md +98 -0
  64. package/templates/agents/seo-content-writer.agent.md +76 -0
  65. package/templates/agents/seo-keyword-strategist.agent.md +75 -0
  66. package/templates/agents/seo-meta-optimizer.agent.md +72 -0
  67. package/templates/agents/seo-snippet-hunter.agent.md +94 -0
  68. package/templates/agents/seo-structure-architect.agent.md +88 -0
  69. package/templates/agents/service-mesh-expert.agent.md +41 -0
  70. package/templates/agents/sql-pro.agent.md +146 -0
  71. package/templates/agents/tdd-orchestrator.agent.md +183 -0
  72. package/templates/agents/temporal-python-pro.agent.md +349 -0
  73. package/templates/agents/terraform-specialist.agent.md +137 -0
  74. package/templates/agents/test-automator.agent.md +203 -0
  75. package/templates/agents/threat-modeling-expert.agent.md +44 -0
  76. package/templates/agents/tutorial-engineer.agent.md +118 -0
  77. package/templates/agents/ui-ux-designer.agent.md +188 -0
  78. package/templates/agents/ui-visual-validator.agent.md +192 -0
  79. package/templates/agents/vector-database-engineer.agent.md +43 -0
  80. package/templates/skills/angular-migration/SKILL.md +410 -0
  81. package/templates/skills/api-design-principles/SKILL.md +528 -0
  82. package/templates/skills/api-design-principles/assets/api-design-checklist.md +155 -0
  83. package/templates/skills/api-design-principles/assets/rest-api-template.py +182 -0
  84. package/templates/skills/api-design-principles/references/graphql-schema-design.md +583 -0
  85. package/templates/skills/api-design-principles/references/rest-best-practices.md +408 -0
  86. package/templates/skills/architecture-decision-records/SKILL.md +428 -0
  87. package/templates/skills/architecture-patterns/SKILL.md +494 -0
  88. package/templates/skills/async-python-patterns/SKILL.md +694 -0
  89. package/templates/skills/auth-implementation-patterns/SKILL.md +634 -0
  90. package/templates/skills/changelog-automation/SKILL.md +552 -0
  91. package/templates/skills/code-review-excellence/SKILL.md +520 -0
  92. package/templates/skills/competitive-landscape/SKILL.md +479 -0
  93. package/templates/skills/context-driven-development/SKILL.md +385 -0
  94. package/templates/skills/cost-optimization/SKILL.md +274 -0
  95. package/templates/skills/cqrs-implementation/SKILL.md +554 -0
  96. package/templates/skills/data-quality-frameworks/SKILL.md +587 -0
  97. package/templates/skills/data-storytelling/SKILL.md +453 -0
  98. package/templates/skills/database-migration/SKILL.md +424 -0
  99. package/templates/skills/dbt-transformation-patterns/SKILL.md +561 -0
  100. package/templates/skills/debugging-strategies/SKILL.md +527 -0
  101. package/templates/skills/defi-protocol-templates/SKILL.md +454 -0
  102. package/templates/skills/dependency-upgrade/SKILL.md +409 -0
  103. package/templates/skills/deployment-pipeline-design/SKILL.md +359 -0
  104. package/templates/skills/distributed-tracing/SKILL.md +438 -0
  105. package/templates/skills/dotnet-backend-patterns/SKILL.md +815 -0
  106. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +523 -0
  107. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +336 -0
  108. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +544 -0
  109. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +355 -0
  110. package/templates/skills/e2e-testing-patterns/SKILL.md +547 -0
  111. package/templates/skills/employment-contract-templates/SKILL.md +507 -0
  112. package/templates/skills/error-handling-patterns/SKILL.md +636 -0
  113. package/templates/skills/event-store-design/SKILL.md +437 -0
  114. package/templates/skills/fastapi-templates/SKILL.md +567 -0
  115. package/templates/skills/git-advanced-workflows/SKILL.md +400 -0
  116. package/templates/skills/github-actions-templates/SKILL.md +333 -0
  117. package/templates/skills/go-concurrency-patterns/SKILL.md +655 -0
  118. package/templates/skills/grafana-dashboards/SKILL.md +369 -0
  119. package/templates/skills/helm-chart-scaffolding/SKILL.md +544 -0
  120. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +42 -0
  121. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +185 -0
  122. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +500 -0
  123. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +244 -0
  124. package/templates/skills/javascript-testing-patterns/SKILL.md +1025 -0
  125. package/templates/skills/langchain-architecture/SKILL.md +338 -0
  126. package/templates/skills/llm-evaluation/SKILL.md +471 -0
  127. package/templates/skills/microservices-patterns/SKILL.md +595 -0
  128. package/templates/skills/modern-javascript-patterns/SKILL.md +911 -0
  129. package/templates/skills/monorepo-management/SKILL.md +622 -0
  130. package/templates/skills/nextjs-app-router-patterns/SKILL.md +544 -0
  131. package/templates/skills/nodejs-backend-patterns/SKILL.md +1020 -0
  132. package/templates/skills/nx-workspace-patterns/SKILL.md +452 -0
  133. package/templates/skills/openapi-spec-generation/SKILL.md +1028 -0
  134. package/templates/skills/paypal-integration/SKILL.md +467 -0
  135. package/templates/skills/pci-compliance/SKILL.md +466 -0
  136. package/templates/skills/postgresql/SKILL.md +204 -0
  137. package/templates/skills/projection-patterns/SKILL.md +490 -0
  138. package/templates/skills/prometheus-configuration/SKILL.md +392 -0
  139. package/templates/skills/prompt-engineering-patterns/SKILL.md +201 -0
  140. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +106 -0
  141. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +246 -0
  142. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +399 -0
  143. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +369 -0
  144. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +414 -0
  145. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +470 -0
  146. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +189 -0
  147. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +279 -0
  148. package/templates/skills/python-packaging/SKILL.md +870 -0
  149. package/templates/skills/python-performance-optimization/SKILL.md +869 -0
  150. package/templates/skills/python-testing-patterns/SKILL.md +907 -0
  151. package/templates/skills/rag-implementation/SKILL.md +403 -0
  152. package/templates/skills/react-modernization/SKILL.md +513 -0
  153. package/templates/skills/react-native-architecture/SKILL.md +671 -0
  154. package/templates/skills/react-state-management/SKILL.md +429 -0
  155. package/templates/skills/risk-metrics-calculation/SKILL.md +555 -0
  156. package/templates/skills/rust-async-patterns/SKILL.md +517 -0
  157. package/templates/skills/secrets-management/SKILL.md +346 -0
  158. package/templates/skills/security-requirement-extraction/SKILL.md +677 -0
  159. package/templates/skills/shellcheck-configuration/SKILL.md +454 -0
  160. package/templates/skills/similarity-search-patterns/SKILL.md +558 -0
  161. package/templates/skills/slo-implementation/SKILL.md +329 -0
  162. package/templates/skills/sql-optimization-patterns/SKILL.md +493 -0
  163. package/templates/skills/stripe-integration/SKILL.md +442 -0
  164. package/templates/skills/tailwind-design-system/SKILL.md +666 -0
  165. package/templates/skills/temporal-python-testing/SKILL.md +158 -0
  166. package/templates/skills/temporal-python-testing/resources/integration-testing.md +455 -0
  167. package/templates/skills/temporal-python-testing/resources/local-setup.md +553 -0
  168. package/templates/skills/temporal-python-testing/resources/replay-testing.md +462 -0
  169. package/templates/skills/temporal-python-testing/resources/unit-testing.md +328 -0
  170. package/templates/skills/terraform-module-library/SKILL.md +249 -0
  171. package/templates/skills/terraform-module-library/references/aws-modules.md +63 -0
  172. package/templates/skills/threat-mitigation-mapping/SKILL.md +745 -0
  173. package/templates/skills/track-management/SKILL.md +593 -0
  174. package/templates/skills/typescript-advanced-types/SKILL.md +717 -0
  175. package/templates/skills/uv-package-manager/SKILL.md +831 -0
  176. package/templates/skills/vector-index-tuning/SKILL.md +521 -0
  177. package/templates/skills/wcag-audit-patterns/SKILL.md +555 -0
  178. package/templates/skills/workflow-orchestration-patterns/SKILL.md +316 -0
  179. package/templates/skills/workflow-patterns/SKILL.md +623 -0
  180. package/templates/agents/game-developer.agent.md +0 -57
  181. package/templates/agents/kubernetes-specialist.agent.md +0 -56
  182. package/templates/agents/market-researcher.agent.md +0 -47
@@ -0,0 +1,655 @@
1
+ ---
2
+ name: go-concurrency-patterns
3
+ description: Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions.
4
+ ---
5
+
6
+ # Go Concurrency Patterns
7
+
8
+ Production patterns for Go concurrency including goroutines, channels, synchronization primitives, and context management.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Building concurrent Go applications
13
+ - Implementing worker pools and pipelines
14
+ - Managing goroutine lifecycles
15
+ - Using channels for communication
16
+ - Debugging race conditions
17
+ - Implementing graceful shutdown
18
+
19
+ ## Core Concepts
20
+
21
+ ### 1. Go Concurrency Primitives
22
+
23
+ | Primitive | Purpose |
24
+ |-----------|---------|
25
+ | `goroutine` | Lightweight concurrent execution |
26
+ | `channel` | Communication between goroutines |
27
+ | `select` | Multiplex channel operations |
28
+ | `sync.Mutex` | Mutual exclusion |
29
+ | `sync.WaitGroup` | Wait for goroutines to complete |
30
+ | `context.Context` | Cancellation and deadlines |
31
+
32
+ ### 2. Go Concurrency Mantra
33
+
34
+ ```
35
+ Don't communicate by sharing memory;
36
+ share memory by communicating.
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ```go
42
+ package main
43
+
44
+ import (
45
+ "context"
46
+ "fmt"
47
+ "sync"
48
+ "time"
49
+ )
50
+
51
+ func main() {
52
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
53
+ defer cancel()
54
+
55
+ results := make(chan string, 10)
56
+ var wg sync.WaitGroup
57
+
58
+ // Spawn workers
59
+ for i := 0; i < 3; i++ {
60
+ wg.Add(1)
61
+ go worker(ctx, i, results, &wg)
62
+ }
63
+
64
+ // Close results when done
65
+ go func() {
66
+ wg.Wait()
67
+ close(results)
68
+ }()
69
+
70
+ // Collect results
71
+ for result := range results {
72
+ fmt.Println(result)
73
+ }
74
+ }
75
+
76
+ func worker(ctx context.Context, id int, results chan<- string, wg *sync.WaitGroup) {
77
+ defer wg.Done()
78
+
79
+ select {
80
+ case <-ctx.Done():
81
+ return
82
+ case results <- fmt.Sprintf("Worker %d done", id):
83
+ }
84
+ }
85
+ ```
86
+
87
+ ## Patterns
88
+
89
+ ### Pattern 1: Worker Pool
90
+
91
+ ```go
92
+ package main
93
+
94
+ import (
95
+ "context"
96
+ "fmt"
97
+ "sync"
98
+ )
99
+
100
+ type Job struct {
101
+ ID int
102
+ Data string
103
+ }
104
+
105
+ type Result struct {
106
+ JobID int
107
+ Output string
108
+ Err error
109
+ }
110
+
111
+ func WorkerPool(ctx context.Context, numWorkers int, jobs <-chan Job) <-chan Result {
112
+ results := make(chan Result, len(jobs))
113
+
114
+ var wg sync.WaitGroup
115
+ for i := 0; i < numWorkers; i++ {
116
+ wg.Add(1)
117
+ go func(workerID int) {
118
+ defer wg.Done()
119
+ for job := range jobs {
120
+ select {
121
+ case <-ctx.Done():
122
+ return
123
+ default:
124
+ result := processJob(job)
125
+ results <- result
126
+ }
127
+ }
128
+ }(i)
129
+ }
130
+
131
+ go func() {
132
+ wg.Wait()
133
+ close(results)
134
+ }()
135
+
136
+ return results
137
+ }
138
+
139
+ func processJob(job Job) Result {
140
+ // Simulate work
141
+ return Result{
142
+ JobID: job.ID,
143
+ Output: fmt.Sprintf("Processed: %s", job.Data),
144
+ }
145
+ }
146
+
147
+ // Usage
148
+ func main() {
149
+ ctx, cancel := context.WithCancel(context.Background())
150
+ defer cancel()
151
+
152
+ jobs := make(chan Job, 100)
153
+
154
+ // Send jobs
155
+ go func() {
156
+ for i := 0; i < 50; i++ {
157
+ jobs <- Job{ID: i, Data: fmt.Sprintf("job-%d", i)}
158
+ }
159
+ close(jobs)
160
+ }()
161
+
162
+ // Process with 5 workers
163
+ results := WorkerPool(ctx, 5, jobs)
164
+
165
+ for result := range results {
166
+ fmt.Printf("Result: %+v\n", result)
167
+ }
168
+ }
169
+ ```
170
+
171
+ ### Pattern 2: Fan-Out/Fan-In Pipeline
172
+
173
+ ```go
174
+ package main
175
+
176
+ import (
177
+ "context"
178
+ "sync"
179
+ )
180
+
181
+ // Stage 1: Generate numbers
182
+ func generate(ctx context.Context, nums ...int) <-chan int {
183
+ out := make(chan int)
184
+ go func() {
185
+ defer close(out)
186
+ for _, n := range nums {
187
+ select {
188
+ case <-ctx.Done():
189
+ return
190
+ case out <- n:
191
+ }
192
+ }
193
+ }()
194
+ return out
195
+ }
196
+
197
+ // Stage 2: Square numbers (can run multiple instances)
198
+ func square(ctx context.Context, in <-chan int) <-chan int {
199
+ out := make(chan int)
200
+ go func() {
201
+ defer close(out)
202
+ for n := range in {
203
+ select {
204
+ case <-ctx.Done():
205
+ return
206
+ case out <- n * n:
207
+ }
208
+ }
209
+ }()
210
+ return out
211
+ }
212
+
213
+ // Fan-in: Merge multiple channels into one
214
+ func merge(ctx context.Context, cs ...<-chan int) <-chan int {
215
+ var wg sync.WaitGroup
216
+ out := make(chan int)
217
+
218
+ // Start output goroutine for each input channel
219
+ output := func(c <-chan int) {
220
+ defer wg.Done()
221
+ for n := range c {
222
+ select {
223
+ case <-ctx.Done():
224
+ return
225
+ case out <- n:
226
+ }
227
+ }
228
+ }
229
+
230
+ wg.Add(len(cs))
231
+ for _, c := range cs {
232
+ go output(c)
233
+ }
234
+
235
+ // Close out after all inputs are done
236
+ go func() {
237
+ wg.Wait()
238
+ close(out)
239
+ }()
240
+
241
+ return out
242
+ }
243
+
244
+ func main() {
245
+ ctx, cancel := context.WithCancel(context.Background())
246
+ defer cancel()
247
+
248
+ // Generate input
249
+ in := generate(ctx, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
250
+
251
+ // Fan out to multiple squarers
252
+ c1 := square(ctx, in)
253
+ c2 := square(ctx, in)
254
+ c3 := square(ctx, in)
255
+
256
+ // Fan in results
257
+ for result := range merge(ctx, c1, c2, c3) {
258
+ fmt.Println(result)
259
+ }
260
+ }
261
+ ```
262
+
263
+ ### Pattern 3: Bounded Concurrency with Semaphore
264
+
265
+ ```go
266
+ package main
267
+
268
+ import (
269
+ "context"
270
+ "fmt"
271
+ "golang.org/x/sync/semaphore"
272
+ "sync"
273
+ )
274
+
275
+ type RateLimitedWorker struct {
276
+ sem *semaphore.Weighted
277
+ }
278
+
279
+ func NewRateLimitedWorker(maxConcurrent int64) *RateLimitedWorker {
280
+ return &RateLimitedWorker{
281
+ sem: semaphore.NewWeighted(maxConcurrent),
282
+ }
283
+ }
284
+
285
+ func (w *RateLimitedWorker) Do(ctx context.Context, tasks []func() error) []error {
286
+ var (
287
+ wg sync.WaitGroup
288
+ mu sync.Mutex
289
+ errors []error
290
+ )
291
+
292
+ for _, task := range tasks {
293
+ // Acquire semaphore (blocks if at limit)
294
+ if err := w.sem.Acquire(ctx, 1); err != nil {
295
+ return []error{err}
296
+ }
297
+
298
+ wg.Add(1)
299
+ go func(t func() error) {
300
+ defer wg.Done()
301
+ defer w.sem.Release(1)
302
+
303
+ if err := t(); err != nil {
304
+ mu.Lock()
305
+ errors = append(errors, err)
306
+ mu.Unlock()
307
+ }
308
+ }(task)
309
+ }
310
+
311
+ wg.Wait()
312
+ return errors
313
+ }
314
+
315
+ // Alternative: Channel-based semaphore
316
+ type Semaphore chan struct{}
317
+
318
+ func NewSemaphore(n int) Semaphore {
319
+ return make(chan struct{}, n)
320
+ }
321
+
322
+ func (s Semaphore) Acquire() {
323
+ s <- struct{}{}
324
+ }
325
+
326
+ func (s Semaphore) Release() {
327
+ <-s
328
+ }
329
+ ```
330
+
331
+ ### Pattern 4: Graceful Shutdown
332
+
333
+ ```go
334
+ package main
335
+
336
+ import (
337
+ "context"
338
+ "fmt"
339
+ "os"
340
+ "os/signal"
341
+ "sync"
342
+ "syscall"
343
+ "time"
344
+ )
345
+
346
+ type Server struct {
347
+ shutdown chan struct{}
348
+ wg sync.WaitGroup
349
+ }
350
+
351
+ func NewServer() *Server {
352
+ return &Server{
353
+ shutdown: make(chan struct{}),
354
+ }
355
+ }
356
+
357
+ func (s *Server) Start(ctx context.Context) {
358
+ // Start workers
359
+ for i := 0; i < 5; i++ {
360
+ s.wg.Add(1)
361
+ go s.worker(ctx, i)
362
+ }
363
+ }
364
+
365
+ func (s *Server) worker(ctx context.Context, id int) {
366
+ defer s.wg.Done()
367
+ defer fmt.Printf("Worker %d stopped\n", id)
368
+
369
+ ticker := time.NewTicker(time.Second)
370
+ defer ticker.Stop()
371
+
372
+ for {
373
+ select {
374
+ case <-ctx.Done():
375
+ // Cleanup
376
+ fmt.Printf("Worker %d cleaning up...\n", id)
377
+ time.Sleep(500 * time.Millisecond) // Simulated cleanup
378
+ return
379
+ case <-ticker.C:
380
+ fmt.Printf("Worker %d working...\n", id)
381
+ }
382
+ }
383
+ }
384
+
385
+ func (s *Server) Shutdown(timeout time.Duration) {
386
+ // Signal shutdown
387
+ close(s.shutdown)
388
+
389
+ // Wait with timeout
390
+ done := make(chan struct{})
391
+ go func() {
392
+ s.wg.Wait()
393
+ close(done)
394
+ }()
395
+
396
+ select {
397
+ case <-done:
398
+ fmt.Println("Clean shutdown completed")
399
+ case <-time.After(timeout):
400
+ fmt.Println("Shutdown timed out, forcing exit")
401
+ }
402
+ }
403
+
404
+ func main() {
405
+ // Setup signal handling
406
+ ctx, cancel := context.WithCancel(context.Background())
407
+
408
+ sigCh := make(chan os.Signal, 1)
409
+ signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
410
+
411
+ server := NewServer()
412
+ server.Start(ctx)
413
+
414
+ // Wait for signal
415
+ sig := <-sigCh
416
+ fmt.Printf("\nReceived signal: %v\n", sig)
417
+
418
+ // Cancel context to stop workers
419
+ cancel()
420
+
421
+ // Wait for graceful shutdown
422
+ server.Shutdown(5 * time.Second)
423
+ }
424
+ ```
425
+
426
+ ### Pattern 5: Error Group with Cancellation
427
+
428
+ ```go
429
+ package main
430
+
431
+ import (
432
+ "context"
433
+ "fmt"
434
+ "golang.org/x/sync/errgroup"
435
+ "net/http"
436
+ )
437
+
438
+ func fetchAllURLs(ctx context.Context, urls []string) ([]string, error) {
439
+ g, ctx := errgroup.WithContext(ctx)
440
+
441
+ results := make([]string, len(urls))
442
+
443
+ for i, url := range urls {
444
+ i, url := i, url // Capture loop variables
445
+
446
+ g.Go(func() error {
447
+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
448
+ if err != nil {
449
+ return fmt.Errorf("creating request for %s: %w", url, err)
450
+ }
451
+
452
+ resp, err := http.DefaultClient.Do(req)
453
+ if err != nil {
454
+ return fmt.Errorf("fetching %s: %w", url, err)
455
+ }
456
+ defer resp.Body.Close()
457
+
458
+ results[i] = fmt.Sprintf("%s: %d", url, resp.StatusCode)
459
+ return nil
460
+ })
461
+ }
462
+
463
+ // Wait for all goroutines to complete or one to fail
464
+ if err := g.Wait(); err != nil {
465
+ return nil, err // First error cancels all others
466
+ }
467
+
468
+ return results, nil
469
+ }
470
+
471
+ // With concurrency limit
472
+ func fetchWithLimit(ctx context.Context, urls []string, limit int) ([]string, error) {
473
+ g, ctx := errgroup.WithContext(ctx)
474
+ g.SetLimit(limit) // Max concurrent goroutines
475
+
476
+ results := make([]string, len(urls))
477
+ var mu sync.Mutex
478
+
479
+ for i, url := range urls {
480
+ i, url := i, url
481
+
482
+ g.Go(func() error {
483
+ result, err := fetchURL(ctx, url)
484
+ if err != nil {
485
+ return err
486
+ }
487
+
488
+ mu.Lock()
489
+ results[i] = result
490
+ mu.Unlock()
491
+ return nil
492
+ })
493
+ }
494
+
495
+ if err := g.Wait(); err != nil {
496
+ return nil, err
497
+ }
498
+
499
+ return results, nil
500
+ }
501
+ ```
502
+
503
+ ### Pattern 6: Concurrent Map with sync.Map
504
+
505
+ ```go
506
+ package main
507
+
508
+ import (
509
+ "sync"
510
+ )
511
+
512
+ // For frequent reads, infrequent writes
513
+ type Cache struct {
514
+ m sync.Map
515
+ }
516
+
517
+ func (c *Cache) Get(key string) (interface{}, bool) {
518
+ return c.m.Load(key)
519
+ }
520
+
521
+ func (c *Cache) Set(key string, value interface{}) {
522
+ c.m.Store(key, value)
523
+ }
524
+
525
+ func (c *Cache) GetOrSet(key string, value interface{}) (interface{}, bool) {
526
+ return c.m.LoadOrStore(key, value)
527
+ }
528
+
529
+ func (c *Cache) Delete(key string) {
530
+ c.m.Delete(key)
531
+ }
532
+
533
+ // For write-heavy workloads, use sharded map
534
+ type ShardedMap struct {
535
+ shards []*shard
536
+ numShards int
537
+ }
538
+
539
+ type shard struct {
540
+ sync.RWMutex
541
+ data map[string]interface{}
542
+ }
543
+
544
+ func NewShardedMap(numShards int) *ShardedMap {
545
+ m := &ShardedMap{
546
+ shards: make([]*shard, numShards),
547
+ numShards: numShards,
548
+ }
549
+ for i := range m.shards {
550
+ m.shards[i] = &shard{data: make(map[string]interface{})}
551
+ }
552
+ return m
553
+ }
554
+
555
+ func (m *ShardedMap) getShard(key string) *shard {
556
+ // Simple hash
557
+ h := 0
558
+ for _, c := range key {
559
+ h = 31*h + int(c)
560
+ }
561
+ return m.shards[h%m.numShards]
562
+ }
563
+
564
+ func (m *ShardedMap) Get(key string) (interface{}, bool) {
565
+ shard := m.getShard(key)
566
+ shard.RLock()
567
+ defer shard.RUnlock()
568
+ v, ok := shard.data[key]
569
+ return v, ok
570
+ }
571
+
572
+ func (m *ShardedMap) Set(key string, value interface{}) {
573
+ shard := m.getShard(key)
574
+ shard.Lock()
575
+ defer shard.Unlock()
576
+ shard.data[key] = value
577
+ }
578
+ ```
579
+
580
+ ### Pattern 7: Select with Timeout and Default
581
+
582
+ ```go
583
+ func selectPatterns() {
584
+ ch := make(chan int)
585
+
586
+ // Timeout pattern
587
+ select {
588
+ case v := <-ch:
589
+ fmt.Println("Received:", v)
590
+ case <-time.After(time.Second):
591
+ fmt.Println("Timeout!")
592
+ }
593
+
594
+ // Non-blocking send/receive
595
+ select {
596
+ case ch <- 42:
597
+ fmt.Println("Sent")
598
+ default:
599
+ fmt.Println("Channel full, skipping")
600
+ }
601
+
602
+ // Priority select (check high priority first)
603
+ highPriority := make(chan int)
604
+ lowPriority := make(chan int)
605
+
606
+ for {
607
+ select {
608
+ case msg := <-highPriority:
609
+ fmt.Println("High priority:", msg)
610
+ default:
611
+ select {
612
+ case msg := <-highPriority:
613
+ fmt.Println("High priority:", msg)
614
+ case msg := <-lowPriority:
615
+ fmt.Println("Low priority:", msg)
616
+ }
617
+ }
618
+ }
619
+ }
620
+ ```
621
+
622
+ ## Race Detection
623
+
624
+ ```bash
625
+ # Run tests with race detector
626
+ go test -race ./...
627
+
628
+ # Build with race detector
629
+ go build -race .
630
+
631
+ # Run with race detector
632
+ go run -race main.go
633
+ ```
634
+
635
+ ## Best Practices
636
+
637
+ ### Do's
638
+ - **Use context** - For cancellation and deadlines
639
+ - **Close channels** - From sender side only
640
+ - **Use errgroup** - For concurrent operations with errors
641
+ - **Buffer channels** - When you know the count
642
+ - **Prefer channels** - Over mutexes when possible
643
+
644
+ ### Don'ts
645
+ - **Don't leak goroutines** - Always have exit path
646
+ - **Don't close from receiver** - Causes panic
647
+ - **Don't use shared memory** - Unless necessary
648
+ - **Don't ignore context cancellation** - Check ctx.Done()
649
+ - **Don't use time.Sleep for sync** - Use proper primitives
650
+
651
+ ## Resources
652
+
653
+ - [Go Concurrency Patterns](https://go.dev/blog/pipelines)
654
+ - [Effective Go - Concurrency](https://go.dev/doc/effective_go#concurrency)
655
+ - [Go by Example - Goroutines](https://gobyexample.com/goroutines)