-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprograms.html
More file actions
1345 lines (1219 loc) · 72.3 KB
/
Copy pathprograms.html
File metadata and controls
1345 lines (1219 loc) · 72.3 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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Go Runnable Sheet — tiny programs, big lightbulbs</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@500;600;700&family=Atkinson+Hyperlegible:ital,wght@0,400;0,700;1,400&family=JetBrains+Mono:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
<style>
:root{
--paper:#eef6f2;
--ink:#0e2f22;
--ink-soft:#4b6b5c;
--card:#ffffff;
--line:#d5e6dd;
--navy:#0b3d2e;
--c-conc:#00add8;
--c-back:#14805f;
--radius:18px;
--mono:'JetBrains Mono',ui-monospace,monospace;
}
*{box-sizing:border-box;margin:0;padding:0}
html{scroll-behavior:smooth;scroll-padding-top:86px}
@media (prefers-reduced-motion: reduce){ html{scroll-behavior:auto} *{transition:none!important;animation:none!important} }
body{
background:var(--paper);
color:var(--ink);
font-family:'Atkinson Hyperlegible',system-ui,sans-serif;
font-size:16px;line-height:1.55;
}
::selection{background:#bdeedd}
/* ---------------- top nav ---------------- */
.topbar{
position:sticky;top:0;z-index:50;
background:rgba(238,246,242,.88);backdrop-filter:blur(8px);
border-bottom:1px solid var(--line);
}
.topbar-inner{
max-width:1240px;margin:0 auto;padding:10px 20px;
display:flex;align-items:center;gap:10px;overflow-x:auto;
scrollbar-width:none;
}
.topbar-inner::-webkit-scrollbar{display:none}
.brand{
font-family:Fredoka,sans-serif;font-weight:700;font-size:17px;
white-space:nowrap;margin-right:6px;color:var(--navy);
text-decoration:none;flex:0 0 auto;
}
.brand b{color:var(--c-back)}
.chip{
flex:0 0 auto;display:inline-flex;align-items:center;gap:7px;
font-family:Fredoka,sans-serif;font-weight:600;font-size:13.5px;
color:var(--ink);text-decoration:none;
padding:6px 13px;border-radius:99px;background:#fff;
border:1.5px solid var(--line);
transition:transform .12s ease, border-color .12s ease;
}
.chip:hover{transform:translateY(-1px)}
.chip .dot{width:9px;height:9px;border-radius:50%;background:var(--dot)}
.chip.active{border-color:var(--dot);box-shadow:0 0 0 3px color-mix(in srgb,var(--dot) 18%, transparent)}
.chip.swap{background:var(--navy);color:#fff;border-color:var(--navy)}
.chip:focus-visible,a:focus-visible,button:focus-visible,input:focus-visible{
outline:3px solid var(--c-back);outline-offset:2px;
}
/* ---------------- hero ---------------- */
.wrap{max-width:1240px;margin:0 auto;padding:0 20px}
.hero{position:relative;margin-top:64px}
.hero-card{
position:relative;
background:linear-gradient(160deg,#0b3d2e 0%,#0f5c42 60%,#14805f 100%);
border-radius:28px;
padding:56px 48px 44px;
color:#e9f9f1;
overflow:visible;
box-shadow:0 18px 40px -18px rgba(11,61,46,.5);
}
.gopher{
position:absolute;top:-58px;right:6%;width:172px;height:auto;
pointer-events:none;
}
.eyebrow{
display:inline-flex;gap:8px;align-items:center;
font-family:Fredoka,sans-serif;font-weight:600;font-size:12.5px;
letter-spacing:.16em;text-transform:uppercase;color:#9fe5c8;
}
.eyebrow::before{content:"";width:22px;height:3px;border-radius:2px;background:#39d98a}
.hero h1{
font-family:Fredoka,sans-serif;font-weight:700;
font-size:clamp(30px,4.6vw,52px);line-height:1.08;
margin:14px 0 12px;max-width:16ch;
}
.hero h1 .hl{position:relative;white-space:nowrap}
.hero h1 .hl::after{
content:"";position:absolute;left:-2%;right:-2%;bottom:6%;height:.32em;
background:var(--hl);border-radius:4px;z-index:-1;opacity:.9;
}
.hero h1 .hl.a{--hl:#39d98a77} .hero h1 .hl.b{--hl:#00add877}
.hero p.sub{max-width:54ch;color:#c4ecd9;font-size:17px}
.hero p.sub a{color:#9ee7f8}
.searchrow{margin-top:26px;display:flex;gap:12px;flex-wrap:wrap;align-items:center}
.search{
flex:1 1 320px;max-width:520px;display:flex;align-items:center;gap:10px;
background:#fff;border-radius:99px;padding:12px 20px;
border:2px solid transparent;
}
.search:focus-within{border-color:var(--c-back)}
.search svg{flex:0 0 auto}
.search input{
border:0;outline:0;flex:1;font:inherit;font-size:16px;color:var(--ink);
background:transparent;min-width:0;
}
.search kbd{
font-family:var(--mono);font-size:12px;color:var(--ink-soft);
border:1px solid var(--line);border-bottom-width:2px;border-radius:6px;padding:1px 7px;
}
.hits{font-family:Fredoka,sans-serif;font-weight:600;font-size:14px;color:#9fe5c8;min-width:9ch}
/* ---------------- sections ---------------- */
.section{margin-top:64px}
.sec-head{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap;margin-bottom:6px}
.sec-head h2{
font-family:Fredoka,sans-serif;font-weight:700;font-size:28px;
display:flex;align-items:center;gap:12px;
}
.sec-head h2::before{
content:"";width:16px;height:16px;border-radius:5px;background:var(--tint);
transform:rotate(45deg);flex:0 0 auto;
}
.sec-head .whisper{color:var(--ink-soft);font-size:15px}
.grid{
margin-top:18px;
display:grid;grid-template-columns:repeat(auto-fill,minmax(480px,1fr));gap:18px;
}
@media (max-width:560px){ .grid{grid-template-columns:1fr} }
.card{
background:var(--card);
border:1.5px solid var(--line);
border-top:5px solid var(--tint);
border-radius:var(--radius);
padding:18px 20px 16px;
display:flex;flex-direction:column;gap:10px;
transition:transform .15s ease, box-shadow .15s ease;
}
.card:hover{transform:translateY(-3px);box-shadow:0 14px 28px -16px rgba(11,61,46,.35)}
.card h3{
font-family:Fredoka,sans-serif;font-weight:600;font-size:17.5px;
display:flex;align-items:center;gap:8px;
}
.card h3 .num{color:var(--tint);font-weight:700}
.card h3 .tag{
margin-left:auto;font-size:11px;font-weight:600;letter-spacing:.08em;
text-transform:uppercase;color:var(--tint);
background:color-mix(in srgb,var(--tint) 12%, white);
border-radius:99px;padding:3px 10px;
}
.card .what{font-size:14.5px;color:var(--ink-soft)}
.card .use{
font-size:13.5px;color:var(--ink-soft);
border-top:1px dashed var(--line);padding-top:9px;margin-top:auto;
}
.card .use b{color:var(--ink)}
.eli{
background:#fff8e7;border:1px solid #eee0b6;border-radius:10px;
padding:9px 12px;font-size:13.5px;color:#6b5b2e;line-height:1.55;
}
.eli b{color:#8a6d1a}
.eli code{background:#fff;border:1px solid #eee0b6;border-radius:5px;padding:0 4px;font-size:.9em;color:#0b6bcb}
ol.how{margin:0 0 0 20px;font-size:13.5px;color:var(--ink-soft)}
ol.how li{margin:3px 0}
ol.how b{color:var(--ink)}
details.lbl{border:1.5px solid var(--line);border-radius:12px;background:#fbfdfc;overflow:hidden}
details.lbl summary{cursor:pointer;font-family:Fredoka,sans-serif;font-weight:600;font-size:13.5px;padding:10px 14px;color:var(--ink-soft);list-style-position:inside}
details.lbl summary:hover{color:var(--ink)}
details.lbl[open] summary{border-bottom:1px dashed var(--line)}
.ln{padding:9px 14px;border-bottom:1px dashed var(--line);font-size:13px}
.ln:last-child{border-bottom:0}
.ln>code{display:block;font-family:var(--mono);font-size:11.5px;color:#0b5a70;background:#eef6f2;border:1px solid var(--line);border-radius:6px;padding:3px 8px;margin-bottom:5px;white-space:pre-wrap;font-variant-ligatures:none}
.ln p{margin:0;color:var(--ink-soft);line-height:1.55}
.ln b{color:var(--ink)}
/* code */
.codebox{position:relative}
pre{
background:#f0f7f3;
border:1px solid #dcece3;
border-radius:12px;
padding:13px 15px;
overflow-x:auto;
font-family:var(--mono);font-size:12.4px;line-height:1.6;
tab-size:4;font-variant-ligatures:none;
}
code{font-family:var(--mono);font-variant-ligatures:none}
.k{color:#c2186a;font-weight:700}
.t{color:#0b6bcb}
.s{color:#188a4c}
.c{color:#7c948a;font-style:italic}
.n{color:#b45309}
.copy{
position:absolute;top:8px;right:8px;
font-family:Fredoka,sans-serif;font-weight:600;font-size:11.5px;
border:1px solid var(--line);border-radius:8px;background:#fff;
color:var(--ink-soft);padding:3px 9px;cursor:pointer;opacity:0;
transition:opacity .12s ease;
}
.card:hover .copy,.copy:focus-visible{opacity:1}
.copy.done{color:#188a4c;border-color:#188a4c}
p.note code, .use code, .what code{
background:#eef6f2;border:1px solid var(--line);border-radius:5px;
padding:0 5px;font-size:.9em;color:#0b6bcb;
}
/* terminal output */
.term{border-radius:12px;overflow:hidden;border:1px solid #0b3d2e}
.term .tbar{
display:flex;align-items:center;gap:8px;
background:#0b3d2e;color:#9fe5c8;
font-family:var(--mono);font-size:11.5px;
padding:7px 12px;
}
.term .tbar::before{
content:"";width:9px;height:9px;border-radius:50%;
background:#39d98a;box-shadow:16px 0 0 #f5a623, 32px 0 0 #ef5563;
margin-right:26px;flex:0 0 auto;
}
.term pre{
background:#0e2f22;border:0;border-radius:0;
color:#d7f5e6;font-size:12.2px;
}
.term pre .prompt{color:#39d98a;font-weight:700}
.term pre .dim{color:#7fae98;font-style:italic}
/* clone strip */
.clone{
grid-column:1/-1;
background:color-mix(in srgb,var(--tint) 7%, white);
border:1.5px solid color-mix(in srgb,var(--tint) 35%, white);
border-radius:var(--radius);
padding:20px 22px;
}
.clone h3{
font-family:Fredoka,sans-serif;font-weight:700;font-size:19px;margin-bottom:10px;
display:flex;align-items:center;gap:10px;
}
.clone h3::before{content:"▶";display:grid;place-items:center;width:26px;height:26px;
border-radius:50%;background:var(--tint);color:#fff;font-size:12px;flex:0 0 auto}
footer{
margin:80px 0 40px;text-align:center;color:var(--ink-soft);font-size:14px;
}
footer .paw{font-family:Fredoka,sans-serif;font-weight:600;color:var(--navy)}
footer a{color:var(--c-back)}
.hidden{display:none!important}
@media (max-width:760px){
.hero-card{padding:44px 26px 34px}
.gopher{width:120px;top:-40px;right:5%}
.section{margin-top:48px}
}
@media print{
.topbar,.searchrow,.copy,.gopher{display:none!important}
.hero-card{box-shadow:none;color:#000;background:#fff;border:2px solid #000}
.hero p.sub{color:#333}
.card{break-inside:avoid;box-shadow:none}
body{background:#fff}
}
</style>
</head>
<body>
<nav class="topbar" aria-label="Sections">
<div class="topbar-inner">
<a class="brand" href="#top">go<b>cheat</b>.sheet<sup>▶</sup></a>
<a class="chip swap" href="./">← Basics</a>
<a class="chip swap" href="advanced.html">← Advanced</a>
<a class="chip swap" href="concurrency.html">🎓 Interview · M5</a>
<a class="chip swap" href="warmup/">🐣 Warm-up: first API</a>
<a class="chip swap" href="ebook/">📕 REST ebook</a>
<a class="chip swap" href="scale/">🚀 Scale it</a>
<a class="chip" style="--dot:var(--c-conc)" href="#concurrency"><span class="dot"></span>Concurrency lab</a>
<a class="chip" style="--dot:var(--c-back)" href="#backend"><span class="dot"></span>Backend lab</a>
</div>
</nav>
<main class="wrap" id="top">
<header class="hero">
<div class="hero-card">
<svg class="gopher" viewBox="0 0 200 112" aria-hidden="true">
<circle cx="45" cy="38" r="16" fill="#00add8" stroke="#0b2530" stroke-width="3"/>
<circle cx="155" cy="38" r="16" fill="#00add8" stroke="#0b2530" stroke-width="3"/>
<circle cx="45" cy="38" r="7" fill="#8fdcef"/>
<circle cx="155" cy="38" r="7" fill="#8fdcef"/>
<path d="M25 112 Q25 24 100 24 Q175 24 175 112 Z" fill="#00add8" stroke="#0b2530" stroke-width="3"/>
<!-- safety goggles: lab rules -->
<path d="M40 70 L160 70" stroke="#0b2530" stroke-width="5"/>
<rect x="48" y="56" width="46" height="30" rx="13" fill="#ffd166" opacity=".92" stroke="#0b2530" stroke-width="3"/>
<rect x="106" y="56" width="46" height="30" rx="13" fill="#ffd166" opacity=".92" stroke="#0b2530" stroke-width="3"/>
<circle cx="70" cy="72" r="6.5" fill="#0b2530"/>
<circle cx="130" cy="72" r="6.5" fill="#0b2530"/>
<ellipse cx="100" cy="94" rx="13" ry="9" fill="#f5d7b2" stroke="#0b2530" stroke-width="3"/>
<ellipse cx="100" cy="89" rx="5" ry="3.5" fill="#5b4632"/>
<rect x="94" y="98" width="12" height="11" rx="2.5" fill="#fff" stroke="#0b2530" stroke-width="2.5"/>
<rect x="28" y="101" width="27" height="12" rx="6" fill="#f5d7b2" stroke="#0b2530" stroke-width="3"/>
<rect x="145" y="101" width="27" height="12" rx="6" fill="#f5d7b2" stroke="#0b2530" stroke-width="3"/>
</svg>
<span class="eyebrow">Team cheat sheet · Runnable edition · Go 1.25</span>
<h1>Don't just read Go — <span class="hl a">run it</span> and <span class="hl b">break it</span></h1>
<p class="sub">Twelve complete programs, each one a task off a backend dev's
daily list — real SMTP mail, real MySQL queries, a real slow query getting
cancelled. No <code>time.Sleep("fake work")</code> anywhere: every email really
sends (to a local MailHog inbox — swap the host for
<code>smtp.sendgrid.net</code> and it's production SendGrid), every query really
runs against MySQL. Every output below is what actually printed. Copy one, run
it, then change something and see what happens.</p>
<div class="searchrow">
<label class="search">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#4b6b5c" stroke-width="2.5" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
<input id="q" type="search" placeholder="try “mutex”, “pool”, “mysql”, “shutdown”…" aria-label="Search the programs">
<kbd>/</kbd>
</label>
<span class="hits" id="hits"></span>
</div>
</div>
</header>
<!-- ================= CONCURRENCY LAB ================= -->
<section class="section" id="concurrency" style="--tint:var(--c-conc)">
<div class="sec-head"><h2>Concurrency lab</h2><span class="whisper">eight programs, in order — real SMTP, real MySQL, no simulators</span></div>
<div class="grid">
<div class="clone" data-kw="clone repo run git setup install docker mailhog mysql">
<h3>Run them yourself</h3>
<div class="codebox"><pre><code>git clone https://github.com/devthedeveloper/gocheatsheet
cd gocheatsheet/programs
# real infra these programs actually talk to:
docker run -d --name mailhog -p 1025:1025 -p 8025:8025 mailhog/mailhog
docker run -d --name mysql-demo -e MYSQL_ROOT_PASSWORD=secret \
-e MYSQL_DATABASE=notes -p 3306:3306 mysql:8
go run ./01-goroutines # check http://localhost:8025 for the real emails
go run -race ./03-mutex # extra credit: watch Go catch the race</code></pre></div>
</div>
<article class="card" data-kw="goroutine go keyword concurrent email smtp sendgrid mailhog send parallel main dies exit real">
<h3><span class="num">01</span> goroutines <span class="tag">start here</span></h3>
<p class="what">Three users signed up — three welcome emails go out over <b>real SMTP</b>, at the same time.</p>
<p class="eli"><b>💡 Everyday version:</b> <code>go func(){ done <- sendEmail(u) }()</code> is hiring a helper: they start the real SMTP handshake (EHLO, MAIL FROM, RCPT TO, DATA) immediately while you carry on. But <code>main</code> is the shop owner — when the owner locks up, every helper stops mid-call. (Your HTTP server hires these helpers for you, on every request.)</p>
<div class="codebox"><pre><code>// goroutines: three real welcome emails, sent over real SMTP, concurrently.
//
// Points at a local MailHog container (a real SMTP server for dev/test):
// docker run -d --name mailhog -p 1025:1025 -p 8025:8025 mailhog/mailhog
// In production you'd point Host/Port at smtp.sendgrid.net:587 and auth
// with "apikey" / your SendGrid API key — net/smtp doesn't change at all.
package main
import (
"fmt"
"net/smtp"
)
func sendEmail(to string) error {
msg := []byte("To: " + to + "\r\n" +
"Subject: Welcome!\r\n\r\n" +
"Thanks for signing up.\r\n")
// a REAL SMTP conversation: connect, EHLO, MAIL FROM,
// RCPT TO, DATA — over an actual TCP socket to port 1025
return smtp.SendMail("localhost:1025", nil,
"noreply@example.com", []string{to}, msg)
}
func main() {
users := []string{
"asha@example.com",
"ravi@example.com",
"meera@example.com",
}
done := make(chan error, len(users))
for _, u := range users {
go func() { // fires the real SMTP call concurrently
done <- sendEmail(u)
}()
}
for range users {
if err := <-done; err != nil {
fmt.Println("send failed:", err)
continue
}
fmt.Println("✉️ delivered ✓")
}
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>func sendEmail(to string) error {</code><p><b>What:</b> a real function that opens a real SMTP connection. <b>Why:</b> goroutines run plain functions — nothing special is needed to make a function "concurrency-ready".</p></div>
<div class="ln"><code>return smtp.SendMail("localhost:1025", nil, "noreply@example.com", []string{to}, msg)</code><p><b>What:</b> the stdlib does a REAL SMTP conversation over a real TCP socket: EHLO, MAIL FROM, RCPT TO, DATA. <b>Why:</b> MailHog listens on 1025 like any real mail server. In production, this exact line points at smtp.sendgrid.net:587 with an auth.PlainAuth — SendGrid speaks standard SMTP.</p></div>
<div class="ln"><code>done := make(chan error, len(users))</code><p><b>What:</b> a buffered channel — one slot per email — collects each goroutine's result. <b>Why:</b> buffered so a goroutine can drop its result and exit even if main hasn't read the previous one yet; nobody blocks waiting to hand off.</p></div>
<div class="ln"><code>go func() { done <- sendEmail(u) }()</code><p><b>What:</b> starts sendEmail in a NEW goroutine and moves to the next line immediately — the SMTP handshake for THIS user hasn't happened yet. <b>Why:</b> so signup #2's email never waits behind signup #1's. All three real SMTP connections open concurrently.</p></div>
<div class="ln"><code>for range users { if err := <-done; ... }</code><p><b>What:</b> main waits for exactly as many results as emails sent, printing each as it lands. <b>Why:</b> this is what keeps main alive long enough for the real network round-trips to finish — same job wg.Wait() does in the next program, just via a channel instead.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./01-goroutines
✉️ delivered ✓
✉️ delivered ✓
✉️ delivered ✓</pre></div>
<p class="use"><b>Notice:</b> all 3 messages actually landed — <code>curl localhost:8025/api/v2/messages</code> against the real MailHog inbox showed <code>3 messages</code> with the right <code>To:</code> addresses. Point <code>smtp.SendMail</code> at <code>smtp.sendgrid.net:587</code> with your API key as the password and this exact code sends through SendGrid.</p>
</article>
<article class="card" data-kw="waitgroup wg add done wait dashboard aggregate services fan out mysql real queries">
<h3><span class="num">02</span> wg.Wait() <span class="tag">sync</span></h3>
<p class="what"><code>GET /dashboard</code> runs <b>3 real MySQL queries</b> concurrently — and must respond only when ALL of them have returned.</p>
<p class="eli"><b>💡 Everyday version:</b> a WaitGroup is a tally on a whiteboard: <code>wg.Add(1)</code> = “one more query in flight”, <code>wg.Done()</code> = a query crossing itself off, <code>wg.Wait()</code> = you standing at the board, refusing to send the 200 until the tally reads zero.</p>
<ol class="how">
<li><b><code>wg.Add(1)</code> before <code>go</code></b> — write it on the board <em>before</em> the query leaves, or you might check the board while it still says 0 and respond with half a dashboard.</li>
<li><b><code>defer wg.Done()</code> first line inside</b> — the query crosses itself off however it ends, even on a DB error.</li>
<li><b><code>wg.Wait()</code> blocks</b> until the count is back to 0 — then, and only then, the response goes out.</li>
</ol>
<div class="codebox"><pre><code>// wg.Wait: GET /dashboard runs 3 real MySQL queries concurrently,
// then answers only once ALL three have returned.
package main
import (
"database/sql"
"fmt"
"sync"
_ "github.com/go-sql-driver/mysql"
)
func setup(db *sql.DB) {
db.Exec("DROP TABLE IF EXISTS orders, users")
db.Exec(`CREATE TABLE users (id INT PRIMARY KEY)`)
db.Exec(`CREATE TABLE orders (
id INT PRIMARY KEY, total_paisa INT)`)
for i := 1; i <= 500; i++ {
db.Exec("INSERT INTO users VALUES (?)", i)
}
for i := 1; i <= 1200; i++ {
db.Exec("INSERT INTO orders VALUES (?, ?)",
i, 19900+(i%5)*500)
}
}
func main() {
db, err := sql.Open("mysql",
"root:secret@tcp(localhost:3306)/notes")
if err != nil {
panic(err)
}
defer db.Close()
setup(db) // seed data, so this file is rerunnable standalone
var (
wg sync.WaitGroup
userCount, orderCount int
revenuePaisa int64
)
fmt.Println("GET /dashboard → 3 real queries, in parallel…")
wg.Add(1) // one more query in flight
go func() {
defer wg.Done() // crossed off, always
db.QueryRow("SELECT COUNT(*) FROM users").
Scan(&userCount)
}()
wg.Add(1)
go func() {
defer wg.Done()
db.QueryRow("SELECT COUNT(*) FROM orders").
Scan(&orderCount)
}()
wg.Add(1)
go func() {
defer wg.Done()
db.QueryRow("SELECT COALESCE(SUM(total_paisa),0) " +
"FROM orders").Scan(&revenuePaisa)
}()
wg.Wait() // block here until all three queries return
fmt.Printf("users: %d\n", userCount)
fmt.Printf("orders: %d\n", orderCount)
fmt.Printf("revenue: ₹%.2f\n", float64(revenuePaisa)/100)
fmt.Println("200 OK — response assembled ✓")
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>var ( wg sync.WaitGroup; userCount, orderCount int; revenuePaisa int64 )</code><p><b>What:</b> the counter, plus the real variables each query will fill in. <b>Why:</b> this counter will track "how many queries are still in flight" — zero value ready, no setup needed.</p></div>
<div class="ln"><code>wg.Add(1) (before each go func)</code><p><b>What:</b> counter goes 0→1→2→3: "one more real query is running". <b>Why:</b> it MUST happen before `go`, in the parent goroutine. If the query goroutine did its own Add, main could reach Wait while the counter still reads 0 — and respond before the query even started.</p></div>
<div class="ln"><code>go func() { defer wg.Done(); db.QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount) }()</code><p><b>What:</b> fires a real query against MySQL in its own goroutine, and schedules the countdown for whenever it returns. <b>Why:</b> `defer wg.Done()` fires even if the query errors — a broken connection can't leave the counter stuck above 0, which would hang wg.Wait() forever.</p></div>
<div class="ln"><code>db.QueryRow(...).Scan(&revenuePaisa)</code><p><b>What:</b> runs a real aggregate query and copies the single result column into a real variable via a pointer. <b>Why:</b> three genuinely different SQL statements, three genuinely separate connections from the pool — this is real concurrent database load, not three prints pretending to be one.</p></div>
<div class="ln"><code>wg.Wait()</code><p><b>What:</b> main STOPS here. Zero CPU, until the counter is back to 0. <b>Why:</b> the slowest of the three real queries decides when this returns — same principle as network fan-out, just against a database instead of other services.</p></div>
<div class="ln"><code>fmt.Printf("revenue: ₹%.2f\n", ...)</code><p><b>What:</b> runs only after every query has actually returned real data. <b>Why:</b> past Wait, all three variables are GUARANTEED populated from the database — safe to assemble the dashboard response.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./02-waitgroup
GET /dashboard → 3 real queries, in parallel…
users: 500
orders: 1200
revenue: ₹250800.00
200 OK — response assembled ✓</pre></div>
<p class="use"><b>Notice:</b> <code>users: 500</code>, <code>orders: 1200</code>, <code>revenue: ₹250800.00</code> — real <code>COUNT(*)</code> and <code>SUM(...)</code> against real seeded tables, all three fired at once instead of one after another.</p>
</article>
<article class="card" data-kw="mutex race data race wallet balance cashback money lock unlock lost updates real">
<h3><span class="num">03</span> mutex vs the wallet race <span class="tag">the big one</span></h3>
<p class="what">A cashback promo: 100 concurrent clients, 1,000 hits each, ₹1 per hit. Watch real money vanish.</p>
<p class="eli"><b>💡 Everyday version:</b> two requests read balance ₹500 at the same moment, both compute ₹501, both write ₹501 — one rupee gone. At scale that’s the 😱 line below. The mutex is the single bathroom key at a petrol station: <code>Lock()</code> takes the key, everyone queues, <code>Unlock()</code> hands it back. One goroutine touches the balance at a time.</p>
<div class="codebox"><pre><code>// mutex: 100 concurrent clients earn ₹1 cashback per hit.
package main
import (
"fmt"
"sync"
)
func main() {
const clients, hits = 100, 1000
var wg sync.WaitGroup
// BROKEN: every request credits the wallet, no lock
balance := 0
for range clients {
wg.Add(1)
go func() {
defer wg.Done()
for range hits {
balance++ // RACE: read, add, write
}
}()
}
wg.Wait()
// FIXED: same traffic, one mutex
var mu sync.Mutex
safe := 0
for range clients {
wg.Add(1)
go func() {
defer wg.Done()
for range hits {
mu.Lock()
safe++
mu.Unlock()
}
}()
}
wg.Wait()
fmt.Println("should be: ₹", clients*hits)
fmt.Println("no mutex: ₹", balance, "— money vanished 😱")
fmt.Println("mutex: ₹", safe, "✓")
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>const clients, hits = 100, 1000</code><p><b>What:</b> 100 concurrent clients, each earning cashback 1,000 times. <b>Why:</b> enough volume that the race loses money on every run. Small numbers can get lucky and hide the bug — that's what makes races evil.</p></div>
<div class="ln"><code>balance := 0</code><p><b>What:</b> one plain int, shared by all 100 goroutines. <b>Why:</b> sharing is the point — and sharing without protection is the bug we're about to watch.</p></div>
<div class="ln"><code>balance++</code><p><b>What:</b> looks like one step; is actually three: READ balance, ADD 1, WRITE it back. <b>Why:</b> two clients both read ₹500, both compute ₹501, both write ₹501 — two credits happened, balance moved by one. Repeat thousands of times: tens of thousands of rupees gone.</p></div>
<div class="ln"><code>var mu sync.Mutex</code><p><b>What:</b> the lock. Zero value ready, like WaitGroup. <b>Why:</b> think: ONE bathroom key for the whole petrol station. It protects whatever you consistently lock around — here, the balance.</p></div>
<div class="ln"><code>mu.Lock()</code><p><b>What:</b> take the key — or stand in line until whoever has it gives it back. <b>Why:</b> from this line to Unlock, no other goroutine can be in this section. Read-add-write becomes one uninterruptible turn.</p></div>
<div class="ln"><code>safe++</code><p><b>What:</b> the same three steps as before — <b>Why:</b> — but now nobody can interleave with them. Every credit lands.</p></div>
<div class="ln"><code>mu.Unlock()</code><p><b>What:</b> hand the key back immediately. <b>Why:</b> keep the locked section as short as possible: everything inside it runs one-goroutine-at-a-time, so a fat locked section becomes your bottleneck.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./03-mutex
should be: ₹ 100000
no mutex: ₹ 57307 — money vanished 😱
mutex: ₹ 100000 ✓
<span class="dim"># balance++ is really: read, add 1, write —
# two clients interleave those steps and one
# write overwrites the other. Real money, gone.</span></pre></div>
<p class="use"><b>Extra credit:</b> <code>go run -race ./03-mutex</code> — Go names the exact racing line. This bug passes code review constantly; <code>-race</code> in CI is what actually catches it.</p>
</article>
<article class="card" data-kw="channel send receive close range upload hash sha256 disk file real pipeline hand off">
<h3><span class="num">04</span> channels <span class="tag">pipes</span></h3>
<p class="what">Uploaded files, checksummed as they land — <b>real disk writes, real SHA-256</b>, hand to hand.</p>
<p class="eli"><b>💡 Everyday version:</b> the channel is the hatch between two desks. Unbuffered means hand-to-hand: the upload goroutine stands there holding the open <code>invoice_jan.pdf</code> until the hasher takes it. That’s why the output alternates instead of uploading everything first.</p>
<div class="codebox"><pre><code>// channels: uploaded files, checksummed as they land — hand to hand.
package main
import (
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "uploads")
defer os.RemoveAll(dir)
uploads := make(chan string) // the hand-off point: file paths
go func() { // goroutine A: receives the uploads
docs := map[string]string{
"invoice_jan.pdf": "invoice January contents",
"invoice_feb.pdf": "invoice February contents",
"salary_slip.pdf": "salary slip contents",
}
for name, body := range docs {
path := filepath.Join(dir, name)
os.WriteFile(path, []byte(body), 0o644) // REAL disk write
fmt.Println("upload complete:", name)
uploads <- path // hand the real file to the hasher
}
close(uploads) // no more uploads today
}()
for path := range uploads { // main: hashes each real file
f, _ := os.Open(path)
h := sha256.New()
io.Copy(h, f) // REAL bytes read off disk, REAL hash computed
f.Close()
fmt.Printf(" sha256 %.12x %s\n",
h.Sum(nil), filepath.Base(path))
}
fmt.Println("all uploads processed ✓")
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>dir, _ := os.MkdirTemp("", "uploads")</code><p><b>What:</b> creates a REAL temp directory on disk for this run. <b>Why:</b> no placeholder filenames — the files that get hashed below genuinely exist on the filesystem.</p></div>
<div class="ln"><code>uploads := make(chan string)</code><p><b>What:</b> the hand-off point. Capacity 0 — nothing queues invisibly. <b>Why:</b> unbuffered: the sender physically waits for a receiver. Every "upload" is a live hand-off, not a silent pile-up.</p></div>
<div class="ln"><code>os.WriteFile(path, []byte(body), 0o644)</code><p><b>What:</b> a REAL write to disk — the file genuinely exists after this line. <b>Why:</b> stands in for "the upload finished landing on disk", which in a real service is exactly what a multipart form handler does before scanning.</p></div>
<div class="ln"><code>uploads <- path</code><p><b>What:</b> sends the real file path — BLOCKS until the hasher goroutine receives it. <b>Why:</b> this blocking is free backpressure: the uploader can't get more than one file ahead of the hasher.</p></div>
<div class="ln"><code>close(uploads)</code><p><b>What:</b> marks the channel "no more uploads today". <b>Why:</b> always the SENDER closes — only it knows when it's done. This is what lets the receiving loop end instead of hanging forever.</p></div>
<div class="ln"><code>f, _ := os.Open(path); h := sha256.New(); io.Copy(h, f)</code><p><b>What:</b> opens the REAL file and streams its REAL bytes through a REAL SHA-256 hasher. <b>Why:</b> io.Copy reads in chunks — this scales to large files without loading them fully into memory. The resulting hash is genuinely derived from the file's contents.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./04-channels
upload complete: invoice_jan.pdf
upload complete: invoice_feb.pdf
sha256 3c874aa89195e58c4ec55edf invoice_jan.pdf
sha256 2121a3ff48d8443591818343 invoice_feb.pdf
upload complete: salary_slip.pdf
sha256 8efcbd928fa1c3b3340bc80d salary_slip.pdf
all uploads processed ✓</pre></div>
<p class="use"><b>Notice:</b> those are real <code>sha256</code> digests of real bytes written to a real temp directory (<code>os.MkdirTemp</code>) — not placeholder strings. This is the shape of a real upload → antivirus/dedupe pipeline.</p>
</article>
<article class="card" data-kw="select timeout cache mysql sleep fastest race budget 504 time.After real">
<h3><span class="num">05</span> select + timeout <span class="tag">wait smart</span></h3>
<p class="what"><code>cart:42</code> lives in an in-memory cache AND MySQL. Serve whichever answers first — inside a real 100ms budget.</p>
<p class="eli"><b>💡 Everyday version:</b> you ordered from two food apps; you’ll eat whichever arrives first, and if nothing shows in 30 minutes you’re making noodles. <code>select</code> watches all three cases at once; <code>time.After</code> is the noodles. The user gets an answer in 100ms <em>no matter what</em> the database is doing.</p>
<div class="codebox"><pre><code>// select: an in-process cache vs a genuinely slow MySQL query —
// serve whichever answers first, inside a real time budget.
package main
import (
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
// a real (tiny) in-memory cache — no network, just a map
var cartCache = map[string]string{
"cart:42": "3 items (cache)",
}
func cacheGet(key string) <-chan string {
ch := make(chan string, 1)
go func() {
if v, ok := cartCache[key]; ok {
ch <- v // real map lookup, no artificial delay needed
}
}()
return ch
}
func dbQuery(db *sql.DB, key string) <-chan string {
ch := make(chan string, 1)
go func() {
var dummy int
// SLEEP(3) runs INSIDE MySQL — a genuinely slow query,
// not a Go-side time.Sleep pretending to be one
err := db.QueryRow("SELECT SLEEP(3)").Scan(&dummy)
if err == nil {
ch <- key + " → 3 items (db, after a real 3s query)"
}
}()
return ch
}
func main() {
db, err := sql.Open("mysql",
"root:secret@tcp(localhost:3306)/notes")
if err != nil {
panic(err)
}
defer db.Close()
cache := cacheGet("cart:42")
dbCh := dbQuery(db, "cart:42")
select {
case v := <-cache:
fmt.Println("hit:", v)
case v := <-dbCh:
fmt.Println("hit:", v)
case <-time.After(100 * time.Millisecond):
fmt.Println("both slow → 504, don't hang")
}
fmt.Println("responded within the 100ms budget ✓")
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>var cartCache = map[string]string{"cart:42": ...}</code><p><b>What:</b> a real in-memory cache — just a Go map, no network involved. <b>Why:</b> this is what an actual process-local cache looks like before someone reaches for Redis: a map, a mutex if it's written concurrently, done.</p></div>
<div class="ln"><code>func cacheGet(key string) <-chan string {</code><p><b>What:</b> wraps a real map lookup in a channel so it fits the same shape as the (slow) DB path. <b>Why:</b> select needs channels on every case — even a lookup as fast as this one gets the "return a channel now, deliver later" treatment.</p></div>
<div class="ln"><code>db.QueryRow("SELECT SLEEP(3)").Scan(&dummy)</code><p><b>What:</b> runs a REAL query that genuinely blocks for 3 seconds — inside MySQL itself. <b>Why:</b> this is a standard DBA trick for testing timeouts: SLEEP() makes the server-side delay real, not a Go-side pretend one.</p></div>
<div class="ln"><code>select {</code><p><b>What:</b> waits on ALL cases at once; runs whichever becomes ready FIRST; ignores the rest. <b>Why:</b> one keyword replaces polling loops and "who finished?" bookkeeping.</p></div>
<div class="ln"><code>case <-time.After(100 * time.Millisecond):</code><p><b>What:</b> time.After returns a channel that fires once, 100ms from now. <b>Why:</b> converts "wait for an answer" into "wait AT MOST 100ms" — the user gets a fast 504 instead of a hanging spinner, no matter how slow the real DB query is.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./05-select
hit: 3 items (cache)
responded within the 100ms budget ✓</pre></div>
<p class="use"><b>Notice:</b> the “slow DB” isn’t a Go-side pretend delay — <code>SELECT SLEEP(3)</code> genuinely blocks for 3 real seconds <em>inside MySQL</em>, the same trick DBAs use to test timeouts. The cache (a real map lookup) won before that query got anywhere close to answering.</p>
</article>
<article class="card" data-kw="worker pool queue mysql connections orders fulfillment bounded throughput real">
<h3><span class="num">06</span> worker pool <span class="tag">throughput</span></h3>
<p class="what">9 pending orders need shipping — but the pool is capped at <b>3 real DB connections</b>.</p>
<p class="eli"><b>💡 Everyday version:</b> the 3 connections are baristas; the orders table is the queue. Whoever’s free grabs the next row. Same shape for image resizing, PDF generation, webhook delivery — any pile of jobs where “one goroutine each” would melt something downstream.</p>
<div class="codebox"><pre><code>// worker pool: 9 pending orders, only 3 DB connections fulfilling them.
package main
import (
"database/sql"
"fmt"
"sync"
"time"
_ "github.com/go-sql-driver/mysql"
)
func setup(db *sql.DB) {
db.Exec("DROP TABLE IF EXISTS fulfillment")
db.Exec(`CREATE TABLE fulfillment (
id INT PRIMARY KEY, status VARCHAR(20))`)
for i := 1; i <= 9; i++ {
db.Exec("INSERT INTO fulfillment VALUES (?, 'pending')", i)
}
}
func main() {
db, err := sql.Open("mysql",
"root:secret@tcp(localhost:3306)/notes")
if err != nil {
panic(err)
}
defer db.Close()
db.SetMaxOpenConns(3) // the pool really can't exceed 3 connections
setup(db)
start := time.Now()
orderIDs := make(chan int)
var wg sync.WaitGroup
for conn := 1; conn <= 3; conn++ { // 3 real DB connections
wg.Add(1)
go func(conn int) {
defer wg.Done()
for id := range orderIDs { // until closed
// a REAL write, through a REAL pooled connection
_, err := db.Exec(
"UPDATE fulfillment SET status='shipped' WHERE id=?",
id)
if err != nil {
fmt.Println("update failed:", err)
continue
}
fmt.Printf("conn %d shipped order #%d\n", conn, id)
}
}(conn)
}
for i := 1; i <= 9; i++ {
orderIDs <- i
}
close(orderIDs)
wg.Wait()
var shipped int
db.QueryRow("SELECT COUNT(*) FROM fulfillment WHERE status='shipped'").
Scan(&shipped)
fmt.Printf("%d/9 orders shipped, in %v\n",
shipped, time.Since(start).Round(time.Millisecond))
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>db.SetMaxOpenConns(3)</code><p><b>What:</b> caps the connection pool at exactly 3 — enforced by database/sql itself. <b>Why:</b> this makes "3 workers" a REAL constraint on the database side, not just "3 goroutines happen to exist" while a 4th sneaks a connection anyway.</p></div>
<div class="ln"><code>orderIDs := make(chan int)</code><p><b>What:</b> the shared queue every worker pulls real order IDs from. <b>Why:</b> the channel IS the work distribution — no scheduler, no "which worker is free?" logic anywhere.</p></div>
<div class="ln"><code>for conn := 1; conn <= 3; conn++ { wg.Add(1); go func(conn int) {</code><p><b>What:</b> hires exactly 3 workers, each with its own real DB connection from the pool. <b>Why:</b> the pool size (3) caps how hard you hit MySQL — the ONE number to tune when throughput changes.</p></div>
<div class="ln"><code>db.Exec("UPDATE fulfillment SET status='shipped' WHERE id=?", id)</code><p><b>What:</b> a REAL write against a REAL row — this order is now actually marked shipped in the table. <b>Why:</b> each worker's connection is genuinely separate; MySQL is handling 3 real concurrent writers, not simulated ones.</p></div>
<div class="ln"><code>close(orderIDs)</code><p><b>What:</b> "all 9 orders queued — nothing more is coming." <b>Why:</b> ends every worker's `range` loop. Forget it and all 3 workers wait forever → wg.Wait() deadlocks.</p></div>
<div class="ln"><code>db.QueryRow("SELECT COUNT(*) FROM fulfillment WHERE status='shipped'").Scan(&shipped)</code><p><b>What:</b> a closing REAL query that verifies the real effect of all 9 writes. <b>Why:</b> this is the proof, not a trust-me print statement — if any write failed, this count would show it.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./06-workerpool
conn 3 shipped order #1
conn 1 shipped order #2
conn 3 shipped order #4
conn 2 shipped order #3
conn 1 shipped order #5
conn 2 shipped order #6
conn 3 shipped order #7
conn 1 shipped order #8
conn 2 shipped order #9
9/9 orders shipped, in 7ms</pre></div>
<p class="use"><b>Notice:</b> <code>db.SetMaxOpenConns(3)</code> makes the cap real, not just “3 goroutines happen to exist” — MySQL genuinely never sees a 4th connection. A closing <code>SELECT COUNT(*) ... WHERE status='shipped'</code> proves all 9 rows actually changed.</p>
</article>
<article class="card" data-kw="context cancel timeout report mysql sleep query budget 504 done abort real cancellation">
<h3><span class="num">07</span> context <span class="tag">please stop</span></h3>
<p class="what">A report endpoint with a 400ms budget — a genuinely slow query gets cancelled mid-flight, for real.</p>
<p class="eli"><b>💡 Everyday version:</b> the customer walked out, so the kitchen stops cooking their order. The context is the order ticket every function holds a copy of; when the 400ms timer rings, <code>QueryContext</code> really tells MySQL to abandon the query instead of Go just giving up and hoping.</p>
<div class="codebox"><pre><code>// context: a slow report query, cancelled by the request's real deadline.
package main
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql",
"root:secret@tcp(localhost:3306)/notes")
if err != nil {
panic(err)
}
defer db.Close()
// this endpoint has a 400ms budget
ctx, cancel := context.WithTimeout(
context.Background(), 400*time.Millisecond)
defer cancel() // always, even on success
fmt.Println("generating report (query takes 5s)…")
start := time.Now()
// SELECT SLEEP(5) is a REAL, genuinely slow query — and
// QueryContext really cancels it on the wire when ctx expires
var dummy int
err = db.QueryRowContext(ctx, "SELECT SLEEP(5)").Scan(&dummy)
fmt.Println("took:", time.Since(start).Round(time.Millisecond))
if err != nil {
fmt.Println("aborting report:", err)
fmt.Println("handler: told client 504, moved on")
return
}
fmt.Println("report ready (this line never runs)")
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond)</code><p><b>What:</b> a context whose Done() channel closes automatically after a real 400ms. <b>Why:</b> in a real handler you'd wrap r.Context() instead, so a disconnecting client ALSO cancels the query — same mechanism either way.</p></div>
<div class="ln"><code>defer cancel()</code><p><b>What:</b> releases the context's internal timer when main exits. <b>Why:</b> every WithTimeout leaks a timer+goroutine until cancelled. `go vet` flags a missing cancel; it's non-negotiable.</p></div>
<div class="ln"><code>db.QueryRowContext(ctx, "SELECT SLEEP(5)").Scan(&dummy)</code><p><b>What:</b> runs a REAL 5-second query — but passes ctx in, so the driver can really abort it. <b>Why:</b> THE key idea: QueryContext doesn't just give up locally and hope; the mysql driver actually tells the server to stop, or drops the connection, when ctx fires.</p></div>
<div class="ln"><code>fmt.Println("took:", time.Since(start)...)</code><p><b>What:</b> measures real wall-clock time. <b>Why:</b> the number printed — ~401ms — is the proof: the "5 second" query genuinely got cut off at the 400ms mark, not run to completion in the background.</p></div>
<div class="ln"><code>if err != nil { ... "aborting report", err) }</code><p><b>What:</b> err here really is context.DeadlineExceeded, wrapped by the driver. <b>Why:</b> in a real handler this becomes a 504 — you know EXACTLY why the request failed, not just that it did.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./07-context
generating report (query takes 5s)…
took: 401ms
aborting report: context deadline exceeded
handler: told client 504, moved on</pre></div>
<p class="use"><b>Notice:</b> the query was <code>SELECT SLEEP(5)</code> — a real 5-second query — and the program returned in <code>401ms</code> with the driver’s own <code>context deadline exceeded</code> error. That’s a real cancellation on the wire, not a timer racing a fake sleep.</p>
</article>
<article class="card" data-kw="errgroup checkout payment declined mysql inventory shipment fan out first error x/sync real">
<h3><span class="num">08</span> errgroup <span class="tag">x/sync</span></h3>
<p class="what"><code>POST /checkout</code> fans out to 3 real DB updates — inventory, payment, shipping. The wallet genuinely doesn’t have enough.</p>
<p class="eli"><b>💡 Everyday version:</b> a team lead sends three devs off and waits at standup. Everyone reports; the lead hears the FIRST blocker. It’s the WaitGroup whiteboard from program 02, but workers can also file complaints — which is why it’s the default for real service fan-out.</p>
<div class="codebox"><pre><code>// errgroup: POST /checkout fans out to 3 real DB updates; payment declines.
// needs: go get golang.org/x/sync/errgroup
package main
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/sync/errgroup"
)
func setup(db *sql.DB) {
db.Exec("DROP TABLE IF EXISTS inventory, wallets, shipments")
db.Exec(`CREATE TABLE inventory (sku VARCHAR(20) PRIMARY KEY, stock INT)`)
db.Exec(`CREATE TABLE wallets (user_id INT PRIMARY KEY, balance_paisa INT)`)
db.Exec(`CREATE TABLE shipments (order_id INT PRIMARY KEY, sku VARCHAR(20))`)
db.Exec("INSERT INTO inventory VALUES ('boat-airdopes', 40)")
db.Exec("INSERT INTO wallets VALUES (7, 5000)") // ₹50 — not enough
}
func reserveStock(db *sql.DB, sku string, qty int) error {
res, err := db.Exec(
"UPDATE inventory SET stock = stock - ? WHERE sku=? AND stock >= ?",
qty, sku, qty)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("inventory-service: out of stock")
}
fmt.Println("inventory-service → reserved", qty, sku)
return nil
}
func chargeWallet(db *sql.DB, userID, amountPaisa int) error {
// a REAL conditional UPDATE: only succeeds if balance covers it
res, err := db.Exec(
"UPDATE wallets SET balance_paisa = balance_paisa - ? "+
"WHERE user_id=? AND balance_paisa >= ?",
amountPaisa, userID, amountPaisa)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("payment-service: insufficient balance")
}
fmt.Println("payment-service → charged ₹", amountPaisa/100)
return nil
}
func createShipment(db *sql.DB, orderID int, sku string) error {
_, err := db.Exec(
"INSERT INTO shipments VALUES (?, ?)", orderID, sku)
if err == nil {
fmt.Println("shipping-service → shipment created")
}
return err
}
func main() {
db, err := sql.Open("mysql",
"root:secret@tcp(localhost:3306)/notes")
if err != nil {
panic(err)
}
defer db.Close()
setup(db)
var g errgroup.Group
g.Go(func() error { return reserveStock(db, "boat-airdopes", 1) })
g.Go(func() error { return chargeWallet(db, 7, 249900) }) // ₹2499, wallet has ₹50
g.Go(func() error { return createShipment(db, 1042, "boat-airdopes") })
if err := g.Wait(); err != nil {
fmt.Println("checkout failed:", err)
fmt.Println("→ respond 402, release the reserved stock")
db.Exec("UPDATE inventory SET stock = stock + 1 WHERE sku='boat-airdopes'")
}
}</code></pre></div>
<details class="lbl"><summary>📖 Line by line — what & why</summary>
<div class="ln"><code>var g errgroup.Group</code><p><b>What:</b> the group — zero value ready. Think: WaitGroup with an error slot. <b>Why:</b> from golang.org/x/sync — the one "extra" import that's on every backend team's go.mod anyway.</p></div>
<div class="ln"><code>g.Go(func() error { return reserveStock(db, "boat-airdopes", 1) })</code><p><b>What:</b> starts a REAL conditional UPDATE against the inventory table in its own goroutine. <b>Why:</b> this one line replaces program 02's Add(1) + go + defer Done() — and adds the error plumbing WaitGroup can't do.</p></div>
<div class="ln"><code>res, err := db.Exec("UPDATE wallets SET balance_paisa = balance_paisa - ? WHERE user_id=? AND balance_paisa >= ?", ...)</code><p><b>What:</b> a REAL atomic conditional write: the row updates ONLY if the balance genuinely covers the charge. <b>Why:</b> no application-side "check then update" race here — MySQL evaluates the WHERE and the SET together, in one real statement.</p></div>
<div class="ln"><code>if n, _ := res.RowsAffected(); n == 0 { return errors.New(...) }</code><p><b>What:</b> RowsAffected tells you whether the real UPDATE actually matched a row. <b>Why:</b> zero rows affected here means the WHERE failed — genuinely insufficient balance, not a made-up error string.</p></div>
<div class="ln"><code>if err := g.Wait(); err != nil {</code><p><b>What:</b> blocks like wg.Wait(), then hands you the FIRST real error from the three real DB calls. <b>Why:</b> one line decides the whole checkout's fate — no collecting errors from three channels by hand.</p></div>
<div class="ln"><code>db.Exec("UPDATE inventory SET stock = stock + 1 WHERE sku='boat-airdopes'")</code><p><b>What:</b> a REAL compensating write undoing the real reservation. <b>Why:</b> inventory-service already committed its change and said OK — a failed checkout must genuinely reverse that, with another real statement.</p></div>
</details>
<div class="term"><div class="tbar">terminal</div><pre><span class="prompt">$</span> go run ./08-errgroup
inventory-service → reserved 1 boat-airdopes
shipping-service → shipment created
checkout failed: payment-service: insufficient balance
→ respond 402, release the reserved stock</pre></div>
<p class="use"><b>Notice:</b> the decline isn’t a fake string check — <code>UPDATE wallets SET balance_paisa = balance_paisa - ? WHERE balance_paisa >= ?</code> is a real conditional write; MySQL reports <code>0</code> rows affected because ₹50 truly can’t cover ₹2,499. Inventory and shipping had already succeeded, which is why the failure path explicitly gives the stock back.</p>
</article>
</div>
</section>
<!-- ================= BACKEND LAB ================= -->
<section class="section" id="backend" style="--tint:var(--c-back)">
<div class="sec-head"><h2>Backend lab</h2><span class="whisper">JSON, HTTP, a real database, and dying gracefully</span></div>
<div class="grid">
<article class="card" data-kw="json marshal unmarshal request response order decode encode mysql insert select omitempty real">
<h3><span class="num">09</span> JSON both ways <span class="tag">encoding</span></h3>
<p class="what">Decode a real request body, <b>really insert it</b>, then marshal the row MySQL actually stored.</p>
<p class="eli"><b>💡 Everyday version:</b> your struct is the organized shelf; JSON is the cardboard box on the truck. Unmarshal = unpacking the client’s box onto your shelf; the INSERT is putting it on a real shelf (the database); Marshal packs the response from what’s really there now — not from the request you started with.</p>
<div class="codebox"><pre><code>// json: decode a real request body, save it, marshal the real DB row back.
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Order struct {
ID int `json:"id"`
UserID int `json:"user_id"`
Item string `json:"item"`