-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext-package-guide.html
More file actions
721 lines (633 loc) · 39.4 KB
/
Copy pathcontext-package-guide.html
File metadata and controls
721 lines (633 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Go context Package — Ultimate Guide</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #f6f8fa;
--surface: #ffffff;
--surface2: #f0f2f5;
--border: #d0d7de;
--accent: #0a8060;
--accent2: #0969da;
--accent3: #9a6700;
--accent4: #cf222e;
--text: #1f2328;
--muted: #656d76;
--tag-bg: #dafbe1;
--tag-text: #1a7f37;
--font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
--font-sans: 'Inter', 'Segoe UI', system-ui, sans-serif;
--radius: 12px;
}
html { scroll-behavior: smooth; }
body { background: var(--bg); color: var(--text); font-family: var(--font-sans); line-height: 1.6; padding: 0 0 80px; }
a { color: var(--accent2); text-decoration: none; }
a:hover { text-decoration: underline; }
.hero { background: linear-gradient(135deg,#eaf2ff 0%,#e6f6f1 50%,#f0f8ff 100%); border-bottom: 1px solid var(--border); padding: 72px 24px 60px; text-align: center; position: relative; overflow: hidden; }
.hero::before { content:''; position:absolute; inset:0; background: radial-gradient(ellipse 60% 40% at 30% 60%,rgba(10,128,96,.06) 0%,transparent 70%), radial-gradient(ellipse 50% 40% at 70% 40%,rgba(9,105,218,.05) 0%,transparent 70%); pointer-events:none; }
.hero h1 { font-size:clamp(2rem,5vw,3.4rem); font-weight:800; letter-spacing:-.03em; line-height:1.1; margin-bottom:16px; }
.hero h1 span { color:var(--accent2); }
.hero p { font-size:1.1rem; color:var(--muted); max-width:540px; margin:0 auto 32px; }
.hero-pills { display:flex; flex-wrap:wrap; gap:10px; justify-content:center; }
.hero-pills span { background:var(--surface2); border:1px solid var(--border); border-radius:100px; font-family:var(--font-mono); font-size:.78rem; padding:5px 14px; color:var(--muted); }
.layout { display:grid; grid-template-columns:200px 1fr 220px; max-width:1300px; margin:0 auto; }
.pkg-nav { position:sticky; top:0; height:100vh; overflow-y:auto; padding:32px 0 32px 24px; }
.pkg-list { list-style:none; display:flex; flex-direction:column; gap:4px; }
.pkg-list a { display:flex; align-items:center; gap:8px; font-size:.86rem; font-family:var(--font-mono); color:var(--muted); padding:7px 10px; border-radius:7px; border:1px solid transparent; transition:all .15s; text-decoration:none; }
.pkg-list a:hover { color:var(--text); background:var(--surface); border-color:var(--border); }
.pkg-list a.active { color:var(--accent2); background:rgba(9,105,218,.07); border-color:rgba(9,105,218,.2); font-weight:600; }
.pkg-list a .pkg-icon { font-size:.85rem; width:18px; text-align:center; }
.home-link { display:block; font-weight:700; font-size:.88rem; color:var(--text); padding:4px 10px 18px; letter-spacing:-.01em; text-decoration:none; }
.home-link:hover { color:var(--accent2); text-decoration:none; }
.nav-group { font-size:.62rem; font-weight:700; letter-spacing:.12em; text-transform:uppercase; color:var(--muted); padding:4px 10px 6px; margin-top:8px; }
.toc-nav { position:sticky; top:0; height:100vh; overflow-y:auto; padding:32px 24px 32px 0; }
.toc-title { font-size:.68rem; font-weight:700; letter-spacing:.12em; text-transform:uppercase; color:var(--muted); margin-bottom:12px; padding-left:8px; }
.toc { list-style:none; display:flex; flex-direction:column; gap:2px; }
.toc a { display:block; font-size:.8rem; color:var(--muted); padding:5px 8px; border-radius:6px; border-right:2px solid transparent; transition:all .15s; }
.toc a:hover { color:var(--text); background:var(--surface); border-right-color:var(--accent); text-decoration:none; }
.content { padding:40px 32px; min-width:0; border-left:1px solid var(--border); border-right:1px solid var(--border); }
.section { margin-bottom:60px; scroll-margin-top:24px; }
.section-header { display:flex; align-items:center; gap:12px; margin-bottom:24px; padding-bottom:14px; border-bottom:1px solid var(--border); }
.section-icon { width:36px; height:36px; border-radius:8px; display:grid; place-items:center; font-size:1.1rem; flex-shrink:0; }
.icon-blue { background:rgba(9,105,218,.1); color:var(--accent2); }
.icon-green { background:rgba(10,128,96,.1); color:var(--accent); }
.icon-gold { background:rgba(154,103,0,.1); color:var(--accent3); }
.icon-red { background:rgba(207,34,46,.1); color:var(--accent4); }
.icon-purple { background:rgba(130,80,223,.1); color:#5a32a3; }
.section-header h2 { font-size:1.3rem; font-weight:700; letter-spacing:-.02em; }
.section-header .section-tag { margin-left:auto; font-family:var(--font-mono); font-size:.68rem; background:var(--surface2); border:1px solid var(--border); border-radius:100px; padding:2px 10px; color:var(--muted); }
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; margin-bottom:20px; transition:border-color .2s; }
.card:hover { border-color:#adbac7; }
.card-header { display:flex; align-items:center; justify-content:space-between; padding:14px 18px 12px; border-bottom:1px solid var(--border); background:var(--surface2); }
.card-title { font-size:.9rem; font-weight:600; color:var(--text); }
.card-badge { font-family:var(--font-mono); font-size:.65rem; border-radius:6px; padding:2px 8px; font-weight:600; }
.badge-blue { background:rgba(9,105,218,.08); color:var(--accent2); border:1px solid rgba(9,105,218,.2); }
.badge-green { background:rgba(10,128,96,.08); color:var(--accent); border:1px solid rgba(10,128,96,.2); }
.badge-gold { background:rgba(154,103,0,.08); color:var(--accent3); border:1px solid rgba(154,103,0,.2); }
.badge-red { background:rgba(207,34,46,.08); color:var(--accent4); border:1px solid rgba(207,34,46,.2); }
.badge-purple { background:rgba(130,80,223,.08); color:#5a32a3; border:1px solid rgba(130,80,223,.2); }
.code-wrap { position:relative; padding:20px 20px 18px; }
pre { font-family:var(--font-mono); font-size:.82rem; line-height:1.75; overflow-x:auto; tab-size:4; }
.kw { color:#cf222e; }
.fn { color:#8250df; }
.str { color:#0a3069; }
.cmt { color:#6e7781; font-style:italic; }
.num { color:#0550ae; }
.pkg { color:#0969da; }
.typ { color:#953800; }
.out { color:#1a7f37; }
.callout { display:flex; gap:12px; background:#ddf4ff; border:1px solid #54aeff80; border-radius:8px; padding:14px 16px; margin-bottom:20px; font-size:.86rem; color:#1f2328; }
.callout.warn { background:#fff8c5; border-color:#d4a72c80; }
.callout.tip { background:#dafbe1; border-color:#4ac26b80; }
.callout-icon { flex-shrink:0; font-size:1rem; margin-top:1px; }
.two-col { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
.ref-table { width:100%; border-collapse:collapse; font-size:.83rem; border-radius:var(--radius); overflow:hidden; border:1px solid var(--border); }
.ref-table thead th { background:var(--surface2); padding:10px 14px; text-align:left; font-weight:600; font-size:.75rem; letter-spacing:.05em; text-transform:uppercase; color:var(--muted); border-bottom:1px solid var(--border); }
.ref-table tbody tr { border-bottom:1px solid var(--border); }
.ref-table tbody tr:last-child { border-bottom:none; }
.ref-table tbody tr:hover { background:var(--surface2); }
.ref-table td { padding:9px 14px; vertical-align:top; }
.ref-table td:first-child { font-family:var(--font-mono); font-size:.78rem; color:var(--accent3); white-space:nowrap; }
.ref-table td:nth-child(2) { font-family:var(--font-mono); font-size:.75rem; color:var(--accent2); }
.ref-table td:last-child { color:var(--muted); }
@media(max-width:900px) { .layout{grid-template-columns:1fr} .pkg-nav,.toc-nav{display:none} .content{padding:24px 16px;border:none} .two-col{grid-template-columns:1fr} }
</style>
</head>
<body>
<div class="hero">
<h1>Go <span>context</span> Package</h1>
<p>Propagate cancellation, deadlines, and request-scoped values across goroutines and API boundaries.</p>
<div class="hero-pills">
<span>Background · TODO</span>
<span>WithCancel</span>
<span>WithTimeout</span>
<span>WithDeadline</span>
<span>WithValue</span>
<span>Done · Err</span>
</div>
</div>
<div class="layout">
<nav class="pkg-nav">
<a href="index.html" class="home-link">Go Handbook</a>
<div class="nav-group">Language</div>
<ul class="pkg-list">
<li><a href="basics.html"><span class="pkg-icon">📖</span>Basics</a></li>
<li><a href="data-structures.html"><span class="pkg-icon">📦</span>Data Structures</a></li>
<li><a href="concurrency.html"><span class="pkg-icon">🔀</span>Concurrency</a></li>
<li><a href="testing.html"><span class="pkg-icon">🧪</span>Testing</a></li>
<li><a href="reflection.html"><span class="pkg-icon">🔬</span>Reflection</a></li>
<li><a href="file-data.html"><span class="pkg-icon">📁</span>File & Data</a></li>
<li><a href="web.html"><span class="pkg-icon">🌐</span>Web</a></li>
<li><a href="packages-modules.html"><span class="pkg-icon">🗃</span>Packages & Modules</a></li>
<li><a href="performance.html"><span class="pkg-icon">⚡</span>Performance</a></li>
<li><a href="gotchas.html"><span class="pkg-icon">⚠️</span>Gotchas</a></li>
</ul>
<div class="nav-group">Packages</div>
<ul class="pkg-list">
<li><a href="strings-package-guide.html"><span class="pkg-icon">🔤</span>strings</a></li>
<li><a href="fmt-package-guide.html"><span class="pkg-icon">🖨</span>fmt</a></li>
<li><a href="strconv-package-guide.html"><span class="pkg-icon">🔢</span>strconv</a></li>
<li><a href="sort-package-guide.html"><span class="pkg-icon">📊</span>sort</a></li>
<li><a href="slices-package-guide.html"><span class="pkg-icon">🗂</span>slices</a></li>
<li><a href="io-package-guide.html"><span class="pkg-icon">🔌</span>io</a></li>
<li><a href="os-package-guide.html"><span class="pkg-icon">💻</span>os</a></li>
<li><a href="errors-package-guide.html"><span class="pkg-icon">⚠️</span>errors</a></li>
<li><a href="context-package-guide.html" class="active"><span class="pkg-icon">🎯</span>context</a></li>
<li><a href="time-package-guide.html"><span class="pkg-icon">⏱</span>time</a></li>
<li><a href="math-package-guide.html"><span class="pkg-icon">🧮</span>math</a></li>
</ul>
</nav>
<main class="content">
<!-- ── 1. BACKGROUND & TODO ──────────────────────────── -->
<section class="section" id="roots">
<div class="section-header">
<div class="section-icon icon-blue">🌱</div>
<h2>Root Contexts</h2>
<span class="section-tag">Background · TODO</span>
</div>
<div class="callout">
<span class="callout-icon">ℹ️</span>
<div>Every context tree starts from one of two root values. You never create a context from scratch — you always derive from a root or from another context.</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">context.Background</span>
<span class="card-badge badge-blue">Background</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Background — the top-level root context</span>
<span class="cmt">// Never cancelled, has no deadline, no values</span>
<span class="cmt">// Use as the starting point in main, tests, and</span>
<span class="cmt">// at the top of incoming request handlers</span>
ctx := <span class="pkg">context</span>.<span class="fn">Background</span>()
<span class="cmt">// Typical patterns</span>
<span class="kw">func</span> <span class="fn">main</span>() {
ctx := <span class="pkg">context</span>.<span class="fn">Background</span>()
<span class="fn">run</span>(ctx)
}
<span class="kw">func</span> <span class="fn">handler</span>(w http.<span class="typ">ResponseWriter</span>, r *http.<span class="typ">Request</span>) {
ctx := r.<span class="fn">Context</span>() <span class="cmt">// already set by net/http</span>
<span class="fn">doWork</span>(ctx)
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">context.TODO</span>
<span class="card-badge badge-gold">TODO</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// TODO — a placeholder when you're not yet sure</span>
<span class="cmt">// which context to use, or the calling function</span>
<span class="cmt">// doesn't accept one yet</span>
ctx := <span class="pkg">context</span>.<span class="fn">TODO</span>()
<span class="cmt">// Use TODO to signal "this needs to be wired up"</span>
<span class="cmt">// It behaves identically to Background at runtime</span>
<span class="cmt">// but communicates intent to future readers</span>
<span class="cmt">// Tools like staticcheck can detect TODO contexts</span>
<span class="cmt">// and remind you to replace them</span>
<span class="cmt">// Rule of thumb:</span>
<span class="cmt">// - Background: you know this is the right root</span>
<span class="cmt">// - TODO: you know this is temporary</span></pre>
</div>
</div>
</div>
</section>
<!-- ── 2. WITHCANCEL ─────────────────────────────────── -->
<section class="section" id="cancel">
<div class="section-header">
<div class="section-icon icon-red">❌</div>
<h2>WithCancel</h2>
<span class="section-tag">Manual cancellation</span>
</div>
<div class="callout warn">
<span class="callout-icon">⚠️</span>
<div>Always call the <code>cancel</code> function — even if work completes successfully before cancellation. Failing to call it leaks resources until the parent context is cancelled.</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">WithCancel — cancel on demand</span>
<span class="card-badge badge-red">WithCancel</span>
</div>
<div class="code-wrap">
<pre>ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithCancel</span>(<span class="pkg">context</span>.<span class="fn">Background</span>())
<span class="kw">defer</span> <span class="fn">cancel</span>() <span class="cmt">// always call cancel to free resources</span>
<span class="kw">go func</span>() {
<span class="kw">for</span> {
<span class="kw">select</span> {
<span class="kw">case</span> <-ctx.<span class="fn">Done</span>():
<span class="pkg">fmt</span>.<span class="fn">Println</span>(<span class="str">"worker stopped:"</span>, ctx.<span class="fn">Err</span>())
<span class="cmt">// ctx.Err() == context.Canceled</span>
<span class="kw">return</span>
<span class="kw">default</span>:
<span class="fn">doWork</span>()
}
}
}()
<span class="cmt">// Cancel all derived goroutines when done</span>
<span class="pkg">time</span>.<span class="fn">Sleep</span>(<span class="num">2</span> * <span class="pkg">time</span>.Second)
<span class="fn">cancel</span>() <span class="cmt">// signals ctx.Done() to close</span></pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Cancellation propagates to all children</span>
<span class="card-badge badge-red">Propagation</span>
</div>
<div class="code-wrap">
<pre>parent, cancelParent := <span class="pkg">context</span>.<span class="fn">WithCancel</span>(<span class="pkg">context</span>.<span class="fn">Background</span>())
<span class="kw">defer</span> <span class="fn">cancelParent</span>()
child1, cancel1 := <span class="pkg">context</span>.<span class="fn">WithCancel</span>(parent)
<span class="kw">defer</span> <span class="fn">cancel1</span>()
child2, cancel2 := <span class="pkg">context</span>.<span class="fn">WithCancel</span>(parent)
<span class="kw">defer</span> <span class="fn">cancel2</span>()
<span class="cmt">// Cancelling the parent cancels child1 and child2 too</span>
<span class="fn">cancelParent</span>()
<span class="cmt">// child1.Err() == context.Canceled</span>
<span class="cmt">// child2.Err() == context.Canceled</span>
<span class="cmt">// Cancelling a child does NOT affect the parent or siblings</span>
<span class="fn">cancel1</span>()
<span class="cmt">// parent.Err() == nil (still alive)</span>
<span class="cmt">// child2.Err() == nil (still alive)</span></pre>
</div>
</div>
</section>
<!-- ── 3. WITHTIMEOUT & WITHDEADLINE ─────────────────── -->
<section class="section" id="timeout">
<div class="section-header">
<div class="section-icon icon-gold">⏱</div>
<h2>WithTimeout & WithDeadline</h2>
<span class="section-tag">Time-based cancellation</span>
</div>
<div class="callout tip">
<span class="callout-icon">💡</span>
<div><code>WithTimeout(ctx, d)</code> is shorthand for <code>WithDeadline(ctx, time.Now().Add(d))</code>. Use <code>WithTimeout</code> when you think in durations ("5 seconds"), <code>WithDeadline</code> when you think in absolute times ("until 3pm").</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">WithTimeout</span>
<span class="card-badge badge-gold">WithTimeout</span>
</div>
<div class="code-wrap">
<pre>ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithTimeout</span>(
<span class="pkg">context</span>.<span class="fn">Background</span>(),
<span class="num">5</span>*<span class="pkg">time</span>.Second,
)
<span class="kw">defer</span> <span class="fn">cancel</span>() <span class="cmt">// still call cancel to release early</span>
resp, err := http.<span class="fn">Get</span>(<span class="str">"https://example.com"</span>)
<span class="cmt">// if request takes > 5s, ctx is cancelled</span>
<span class="cmt">// and err wraps context.DeadlineExceeded</span>
<span class="cmt">// Check for timeout specifically</span>
<span class="kw">if</span> <span class="pkg">errors</span>.<span class="fn">Is</span>(err, <span class="pkg">context</span>.DeadlineExceeded) {
<span class="pkg">log</span>.<span class="fn">Println</span>(<span class="str">"request timed out"</span>)
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">WithDeadline</span>
<span class="card-badge badge-gold">WithDeadline</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// WithDeadline — cancel at an absolute time</span>
deadline := <span class="pkg">time</span>.<span class="fn">Now</span>().<span class="fn">Add</span>(<span class="num">10</span> * <span class="pkg">time</span>.Second)
ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithDeadline</span>(
<span class="pkg">context</span>.<span class="fn">Background</span>(),
deadline,
)
<span class="kw">defer</span> <span class="fn">cancel</span>()
<span class="cmt">// Check when the context will expire</span>
dl, ok := ctx.<span class="fn">Deadline</span>()
<span class="kw">if</span> ok {
<span class="pkg">fmt</span>.<span class="fn">Println</span>(<span class="str">"expires at:"</span>, dl)
<span class="pkg">fmt</span>.<span class="fn">Println</span>(<span class="str">"time left:"</span>, <span class="pkg">time</span>.<span class="fn">Until</span>(dl))
}</pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Timeout with database / HTTP — real-world pattern</span>
<span class="card-badge badge-blue">Pattern</span>
</div>
<div class="code-wrap">
<pre><span class="kw">func</span> <span class="fn">fetchUser</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>, id <span class="typ">int</span>) (*<span class="typ">User</span>, <span class="typ">error</span>) {
<span class="cmt">// Apply a local timeout on top of whatever deadline the caller set</span>
ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithTimeout</span>(ctx, <span class="num">3</span>*<span class="pkg">time</span>.Second)
<span class="kw">defer</span> <span class="fn">cancel</span>()
<span class="kw">var</span> user <span class="typ">User</span>
err := db.<span class="fn">QueryRowContext</span>(ctx,
<span class="str">"SELECT * FROM users WHERE id = $1"</span>, id,
).<span class="fn">Scan</span>(&user.ID, &user.Name)
<span class="kw">if</span> err != <span class="kw">nil</span> {
<span class="kw">return</span> <span class="kw">nil</span>, <span class="pkg">fmt</span>.<span class="fn">Errorf</span>(<span class="str">"fetchUser: %w"</span>, err)
}
<span class="kw">return</span> &user, <span class="kw">nil</span>
}
<span class="cmt">// Whichever deadline is sooner — the caller's or the local 3s — wins</span></pre>
</div>
</div>
</section>
<!-- ── 4. DONE, ERR, DEADLINE ────────────────────────── -->
<section class="section" id="methods">
<div class="section-header">
<div class="section-icon icon-green">📡</div>
<h2>Context Methods</h2>
<span class="section-tag">Done · Err · Deadline · Value</span>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">The four methods on context.Context</span>
<span class="card-badge badge-green">Interface</span>
</div>
<div class="code-wrap">
<pre><span class="kw">type</span> <span class="typ">Context</span> <span class="kw">interface</span> {
<span class="cmt">// Done returns a channel that closes when the context is cancelled</span>
<span class="cmt">// or times out. Returns nil for Background and TODO (never closes).</span>
<span class="fn">Done</span>() <-<span class="kw">chan</span> <span class="kw">struct</span>{}
<span class="cmt">// Err returns nil while the context is active.</span>
<span class="cmt">// After Done closes: context.Canceled or context.DeadlineExceeded</span>
<span class="fn">Err</span>() <span class="typ">error</span>
<span class="cmt">// Deadline returns the expiry time if one is set.</span>
<span class="fn">Deadline</span>() (deadline <span class="pkg">time</span>.<span class="typ">Time</span>, ok <span class="typ">bool</span>)
<span class="cmt">// Value returns the value for a key set via WithValue, or nil.</span>
<span class="fn">Value</span>(key <span class="kw">any</span>) <span class="kw">any</span>
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Listening on Done in a select</span>
<span class="card-badge badge-green">Done</span>
</div>
<div class="code-wrap">
<pre><span class="kw">func</span> <span class="fn">processItems</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>, items <-<span class="kw">chan</span> <span class="typ">Item</span>) <span class="typ">error</span> {
<span class="kw">for</span> {
<span class="kw">select</span> {
<span class="kw">case</span> <-ctx.<span class="fn">Done</span>():
<span class="kw">return</span> ctx.<span class="fn">Err</span>() <span class="cmt">// Canceled or DeadlineExceeded</span>
<span class="kw">case</span> item, ok := <-items:
<span class="kw">if</span> !ok {
<span class="kw">return</span> <span class="kw">nil</span> <span class="cmt">// channel closed normally</span>
}
<span class="kw">if</span> err := <span class="fn">process</span>(item); err != <span class="kw">nil</span> {
<span class="kw">return</span> err
}
}
}
}
<span class="cmt">// Check context before expensive operations</span>
<span class="kw">func</span> <span class="fn">doWork</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>) <span class="typ">error</span> {
<span class="kw">if</span> err := ctx.<span class="fn">Err</span>(); err != <span class="kw">nil</span> {
<span class="kw">return</span> err <span class="cmt">// bail early, context already done</span>
}
<span class="cmt">// proceed with work...</span>
<span class="kw">return</span> <span class="kw">nil</span>
}</pre>
</div>
</div>
<div class="two-col">
<div class="card">
<div class="card-header">
<span class="card-title">context.Canceled vs DeadlineExceeded</span>
<span class="card-badge badge-red">Errors</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Two sentinel errors returned by Err()</span>
<span class="pkg">context</span>.Canceled <span class="cmt">// cancel() was called</span>
<span class="pkg">context</span>.DeadlineExceeded <span class="cmt">// timeout/deadline passed</span>
<span class="cmt">// Distinguish with errors.Is</span>
<span class="kw">switch</span> ctx.<span class="fn">Err</span>() {
<span class="kw">case</span> <span class="pkg">context</span>.Canceled:
<span class="pkg">log</span>.<span class="fn">Println</span>(<span class="str">"cancelled by caller"</span>)
<span class="kw">case</span> <span class="pkg">context</span>.DeadlineExceeded:
<span class="pkg">log</span>.<span class="fn">Println</span>(<span class="str">"timed out"</span>)
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Checking remaining time</span>
<span class="card-badge badge-gold">Deadline</span>
</div>
<div class="code-wrap">
<pre>dl, ok := ctx.<span class="fn">Deadline</span>()
<span class="kw">if</span> !ok {
<span class="cmt">// no deadline set — run as long as needed</span>
}
remaining := <span class="pkg">time</span>.<span class="fn">Until</span>(dl)
<span class="kw">if</span> remaining < <span class="num">100</span>*<span class="pkg">time</span>.Millisecond {
<span class="kw">return</span> <span class="pkg">fmt</span>.<span class="fn">Errorf</span>(<span class="str">"not enough time to proceed"</span>)
}
<span class="cmt">// Pass a tighter deadline to a sub-call</span>
subCtx, cancel := <span class="pkg">context</span>.<span class="fn">WithDeadline</span>(ctx,
dl.<span class="fn">Add</span>(-<span class="num">50</span>*<span class="pkg">time</span>.Millisecond), <span class="cmt">// 50ms buffer</span>
)
<span class="kw">defer</span> <span class="fn">cancel</span>()</pre>
</div>
</div>
</div>
</section>
<!-- ── 5. WITHVALUE ──────────────────────────────────── -->
<section class="section" id="values">
<div class="section-header">
<div class="section-icon icon-purple">📦</div>
<h2>WithValue</h2>
<span class="section-tag">Request-scoped data</span>
</div>
<div class="callout warn">
<span class="callout-icon">⚠️</span>
<div>Use <code>WithValue</code> only for request-scoped data that crosses API boundaries — things like trace IDs, auth tokens, or locale. Don't use it as a shortcut for passing optional function parameters.</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">WithValue — typed keys prevent collisions</span>
<span class="card-badge badge-purple">WithValue</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Always use an unexported custom type as the key</span>
<span class="cmt">// so no other package can accidentally read or overwrite it</span>
<span class="kw">type</span> <span class="typ">contextKey</span> <span class="typ">string</span>
<span class="kw">const</span> (
<span class="typ">keyTraceID</span> <span class="typ">contextKey</span> = <span class="str">"traceID"</span>
<span class="typ">keyUserID</span> <span class="typ">contextKey</span> = <span class="str">"userID"</span>
)
<span class="cmt">// Store a value</span>
ctx := <span class="pkg">context</span>.<span class="fn">WithValue</span>(r.<span class="fn">Context</span>(), <span class="typ">keyTraceID</span>, <span class="str">"abc-123"</span>)
ctx = <span class="pkg">context</span>.<span class="fn">WithValue</span>(ctx, <span class="typ">keyUserID</span>, <span class="num">42</span>)
<span class="cmt">// Retrieve a value — returns any, so assert the type</span>
traceID, ok := ctx.<span class="fn">Value</span>(<span class="typ">keyTraceID</span>).(<span class="typ">string</span>)
<span class="kw">if</span> !ok {
traceID = <span class="str">"unknown"</span>
}
userID, _ := ctx.<span class="fn">Value</span>(<span class="typ">keyUserID</span>).(<span class="typ">int</span>)</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Package-level helper functions — the idiomatic pattern</span>
<span class="card-badge badge-purple">Pattern</span>
</div>
<div class="code-wrap">
<pre><span class="cmt">// Define the key type privately in your package</span>
<span class="kw">type</span> <span class="typ">traceKey</span> <span class="kw">struct</span>{}
<span class="cmt">// Expose typed helper functions instead of the raw key</span>
<span class="kw">func</span> <span class="fn">WithTraceID</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>, id <span class="typ">string</span>) <span class="pkg">context</span>.<span class="typ">Context</span> {
<span class="kw">return</span> <span class="pkg">context</span>.<span class="fn">WithValue</span>(ctx, <span class="typ">traceKey</span>{}, id)
}
<span class="kw">func</span> <span class="fn">TraceID</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>) (<span class="typ">string</span>, <span class="typ">bool</span>) {
id, ok := ctx.<span class="fn">Value</span>(<span class="typ">traceKey</span>{}).(<span class="typ">string</span>)
<span class="kw">return</span> id, ok
}
<span class="cmt">// Usage — callers never touch the key directly</span>
ctx = <span class="fn">WithTraceID</span>(ctx, <span class="str">"req-789"</span>)
<span class="kw">if</span> id, ok := <span class="fn">TraceID</span>(ctx); ok {
<span class="pkg">log</span>.<span class="fn">Printf</span>(<span class="str">"trace=%s"</span>, id)
}</pre>
</div>
</div>
</section>
<!-- ── 6. PATTERNS ───────────────────────────────────── -->
<section class="section" id="patterns">
<div class="section-header">
<div class="section-icon icon-blue">📐</div>
<h2>Common Patterns</h2>
<span class="section-tag">HTTP · goroutines · signals</span>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">HTTP server — context flows from request to dependencies</span>
<span class="card-badge badge-blue">HTTP</span>
</div>
<div class="code-wrap">
<pre><span class="kw">func</span> <span class="fn">handler</span>(w http.<span class="typ">ResponseWriter</span>, r *http.<span class="typ">Request</span>) {
<span class="cmt">// r.Context() is cancelled when the client disconnects</span>
ctx := r.<span class="fn">Context</span>()
<span class="cmt">// Add a per-request timeout</span>
ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithTimeout</span>(ctx, <span class="num">5</span>*<span class="pkg">time</span>.Second)
<span class="kw">defer</span> <span class="fn">cancel</span>()
<span class="cmt">// Attach trace ID from incoming header</span>
ctx = <span class="fn">WithTraceID</span>(ctx, r.<span class="fn">Header</span>.<span class="fn">Get</span>(<span class="str">"X-Trace-ID"</span>))
<span class="cmt">// Pass ctx to every downstream call</span>
user, err := <span class="fn">fetchUser</span>(ctx, <span class="num">123</span>)
<span class="kw">if</span> err != <span class="kw">nil</span> {
<span class="kw">if</span> <span class="pkg">errors</span>.<span class="fn">Is</span>(err, <span class="pkg">context</span>.DeadlineExceeded) {
http.<span class="fn">Error</span>(w, <span class="str">"timeout"</span>, http.StatusGatewayTimeout)
<span class="kw">return</span>
}
http.<span class="fn">Error</span>(w, <span class="str">"internal error"</span>, http.StatusInternalServerError)
<span class="kw">return</span>
}
<span class="pkg">json</span>.<span class="fn">NewEncoder</span>(w).<span class="fn">Encode</span>(user)
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Graceful shutdown with os.Signal</span>
<span class="card-badge badge-red">Shutdown</span>
</div>
<div class="code-wrap">
<pre><span class="kw">func</span> <span class="fn">main</span>() {
ctx, stop := <span class="pkg">signal</span>.<span class="fn">NotifyContext</span>(
<span class="pkg">context</span>.<span class="fn">Background</span>(),
<span class="pkg">syscall</span>.SIGINT, <span class="pkg">syscall</span>.SIGTERM,
)
<span class="kw">defer</span> <span class="fn">stop</span>()
server := &http.<span class="typ">Server</span>{Addr: <span class="str">":8080"</span>}
<span class="kw">go func</span>() {
<span class="kw">if</span> err := server.<span class="fn">ListenAndServe</span>(); err != http.ErrServerClosed {
<span class="pkg">log</span>.<span class="fn">Fatal</span>(err)
}
}()
<span class="cmt">// Block until SIGINT or SIGTERM</span>
<-ctx.<span class="fn">Done</span>()
<span class="pkg">log</span>.<span class="fn">Println</span>(<span class="str">"shutting down..."</span>)
shutdownCtx, cancel := <span class="pkg">context</span>.<span class="fn">WithTimeout</span>(
<span class="pkg">context</span>.<span class="fn">Background</span>(), <span class="num">10</span>*<span class="pkg">time</span>.Second,
)
<span class="kw">defer</span> <span class="fn">cancel</span>()
server.<span class="fn">Shutdown</span>(shutdownCtx)
}</pre>
</div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title">Fan-out — cancel all workers when the first fails</span>
<span class="card-badge badge-purple">Fan-out</span>
</div>
<div class="code-wrap">
<pre><span class="kw">func</span> <span class="fn">fetchAll</span>(ctx <span class="pkg">context</span>.<span class="typ">Context</span>, urls []<span class="typ">string</span>) ([]<span class="typ">string</span>, <span class="typ">error</span>) {
ctx, cancel := <span class="pkg">context</span>.<span class="fn">WithCancel</span>(ctx)
<span class="kw">defer</span> <span class="fn">cancel</span>()
results := <span class="fn">make</span>([]<span class="typ">string</span>, <span class="fn">len</span>(urls))
errCh := <span class="fn">make</span>(<span class="kw">chan</span> <span class="typ">error</span>, <span class="fn">len</span>(urls))
<span class="kw">var</span> wg <span class="pkg">sync</span>.<span class="typ">WaitGroup</span>
<span class="kw">for</span> i, url := <span class="kw">range</span> urls {
wg.<span class="fn">Add</span>(<span class="num">1</span>)
<span class="kw">go func</span>(i <span class="typ">int</span>, url <span class="typ">string</span>) {
<span class="kw">defer</span> wg.<span class="fn">Done</span>()
body, err := <span class="fn">fetch</span>(ctx, url)
<span class="kw">if</span> err != <span class="kw">nil</span> {
<span class="fn">cancel</span>() <span class="cmt">// cancel all siblings</span>
errCh <- err
<span class="kw">return</span>
}
results[i] = body
}(i, url)
}
wg.<span class="fn">Wait</span>()
<span class="fn">close</span>(errCh)
<span class="kw">return</span> results, <-errCh
}</pre>
</div>
</div>
</section>
<!-- ── REFERENCE TABLE ───────────────────────────────── -->
<section class="section" id="reference">
<div class="section-header">
<div class="section-icon icon-blue">📋</div>
<h2>Quick Reference</h2>
<span class="section-tag">All key functions & values</span>
</div>
<table class="ref-table">
<thead><tr><th>Function / Value</th><th>Returns</th><th>Description</th></tr></thead>
<tbody>
<tr><td>context.Background()</td><td>Context</td><td>Root context; never cancelled, no deadline, no values</td></tr>
<tr><td>context.TODO()</td><td>Context</td><td>Placeholder root; signals "this should be wired up later"</td></tr>
<tr><td>context.WithCancel(parent)</td><td>Context, CancelFunc</td><td>New context cancelled when parent is or cancel() is called</td></tr>
<tr><td>context.WithTimeout(parent, d)</td><td>Context, CancelFunc</td><td>Cancelled after duration d or when parent is cancelled</td></tr>
<tr><td>context.WithDeadline(parent, t)</td><td>Context, CancelFunc</td><td>Cancelled at absolute time t or when parent is cancelled</td></tr>
<tr><td>context.WithValue(parent, k, v)</td><td>Context</td><td>New context carrying value v under key k</td></tr>
<tr><td>ctx.Done()</td><td><-chan struct{}</td><td>Closed when context is cancelled or times out; nil for Background/TODO</td></tr>
<tr><td>ctx.Err()</td><td>error</td><td>nil while active; Canceled or DeadlineExceeded after Done closes</td></tr>
<tr><td>ctx.Deadline()</td><td>time.Time, bool</td><td>Returns the deadline and whether one is set</td></tr>
<tr><td>ctx.Value(key)</td><td>any</td><td>Returns value stored under key, or nil</td></tr>
<tr><td>context.Canceled</td><td>error</td><td>Sentinel: cancel() was called</td></tr>
<tr><td>context.DeadlineExceeded</td><td>error</td><td>Sentinel: deadline or timeout passed</td></tr>
<tr><td>signal.NotifyContext(ctx, sigs...)</td><td>Context, StopFunc</td><td>Cancel context on OS signals (os/signal package)</td></tr>
</tbody>
</table>
</section>
</main>
<nav class="toc-nav">
<div class="toc-title">On this page</div>
<ul class="toc">
<li><a href="#roots">1 — Root Contexts</a></li>
<li><a href="#cancel">2 — WithCancel</a></li>
<li><a href="#timeout">3 — WithTimeout & WithDeadline</a></li>
<li><a href="#methods">4 — Context Methods</a></li>
<li><a href="#values">5 — WithValue</a></li>
<li><a href="#patterns">6 — Patterns</a></li>
<li><a href="#reference">99 — Quick Reference</a></li>
</ul>
</nav>
</div>
</body>
</html>