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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
|
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// End-to-end serving tests
package http_test
import (
"bufio"
"bytes"
"compress/gzip"
"compress/zlib"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"internal/testenv"
"io"
"log"
"math/rand"
"net"
. "net/http"
"net/http/httptest"
"net/http/httputil"
"net/http/internal"
"net/url"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
)
type dummyAddr string
type oneConnListener struct {
conn net.Conn
}
func (l *oneConnListener) Accept() (c net.Conn, err error) {
c = l.conn
if c == nil {
err = io.EOF
return
}
err = nil
l.conn = nil
return
}
func (l *oneConnListener) Close() error {
return nil
}
func (l *oneConnListener) Addr() net.Addr {
return dummyAddr("test-address")
}
func (a dummyAddr) Network() string {
return string(a)
}
func (a dummyAddr) String() string {
return string(a)
}
type noopConn struct{}
func (noopConn) LocalAddr() net.Addr { return dummyAddr("local-addr") }
func (noopConn) RemoteAddr() net.Addr { return dummyAddr("remote-addr") }
func (noopConn) SetDeadline(t time.Time) error { return nil }
func (noopConn) SetReadDeadline(t time.Time) error { return nil }
func (noopConn) SetWriteDeadline(t time.Time) error { return nil }
type rwTestConn struct {
io.Reader
io.Writer
noopConn
closeFunc func() error // called if non-nil
closec chan bool // else, if non-nil, send value to it on close
}
func (c *rwTestConn) Close() error {
if c.closeFunc != nil {
return c.closeFunc()
}
select {
case c.closec <- true:
default:
}
return nil
}
type testConn struct {
readMu sync.Mutex // for TestHandlerBodyClose
readBuf bytes.Buffer
writeBuf bytes.Buffer
closec chan bool // if non-nil, send value to it on close
noopConn
}
func (c *testConn) Read(b []byte) (int, error) {
c.readMu.Lock()
defer c.readMu.Unlock()
return c.readBuf.Read(b)
}
func (c *testConn) Write(b []byte) (int, error) {
return c.writeBuf.Write(b)
}
func (c *testConn) Close() error {
select {
case c.closec <- true:
default:
}
return nil
}
// reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters,
// ending in \r\n\r\n
func reqBytes(req string) []byte {
return []byte(strings.ReplaceAll(strings.TrimSpace(req), "\n", "\r\n") + "\r\n\r\n")
}
type handlerTest struct {
logbuf bytes.Buffer
handler Handler
}
func newHandlerTest(h Handler) handlerTest {
return handlerTest{handler: h}
}
func (ht *handlerTest) rawResponse(req string) string {
reqb := reqBytes(req)
var output bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(reqb),
Writer: &output,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
srv := &Server{
ErrorLog: log.New(&ht.logbuf, "", 0),
Handler: ht.handler,
}
go srv.Serve(ln)
<-conn.closec
return output.String()
}
func TestConsumingBodyOnNextConn(t *testing.T) {
t.Parallel()
defer afterTest(t)
conn := new(testConn)
for i := 0; i < 2; i++ {
conn.readBuf.Write([]byte(
"POST / HTTP/1.1\r\n" +
"Host: test\r\n" +
"Content-Length: 11\r\n" +
"\r\n" +
"foo=1&bar=1"))
}
reqNum := 0
ch := make(chan *Request)
servech := make(chan error)
listener := &oneConnListener{conn}
handler := func(res ResponseWriter, req *Request) {
reqNum++
ch <- req
}
go func() {
servech <- Serve(listener, HandlerFunc(handler))
}()
var req *Request
req = <-ch
if req == nil {
t.Fatal("Got nil first request.")
}
if req.Method != "POST" {
t.Errorf("For request #1's method, got %q; expected %q",
req.Method, "POST")
}
req = <-ch
if req == nil {
t.Fatal("Got nil first request.")
}
if req.Method != "POST" {
t.Errorf("For request #2's method, got %q; expected %q",
req.Method, "POST")
}
if serveerr := <-servech; serveerr != io.EOF {
t.Errorf("Serve returned %q; expected EOF", serveerr)
}
}
type stringHandler string
func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) {
w.Header().Set("Result", string(s))
}
var handlers = []struct {
pattern string
msg string
}{
{"/", "Default"},
{"/someDir/", "someDir"},
{"/#/", "hash"},
{"someHost.com/someDir/", "someHost.com/someDir"},
}
var vtests = []struct {
url string
expected string
}{
{"http://localhost/someDir/apage", "someDir"},
{"http://localhost/%23/apage", "hash"},
{"http://localhost/otherDir/apage", "Default"},
{"http://someHost.com/someDir/apage", "someHost.com/someDir"},
{"http://otherHost.com/someDir/apage", "someDir"},
{"http://otherHost.com/aDir/apage", "Default"},
// redirections for trees
{"http://localhost/someDir", "/someDir/"},
{"http://localhost/%23", "/%23/"},
{"http://someHost.com/someDir", "/someDir/"},
}
func TestHostHandlers(t *testing.T) {
setParallel(t)
defer afterTest(t)
mux := NewServeMux()
for _, h := range handlers {
mux.Handle(h.pattern, stringHandler(h.msg))
}
ts := httptest.NewServer(mux)
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
cc := httputil.NewClientConn(conn, nil)
for _, vt := range vtests {
var r *Response
var req Request
if req.URL, err = url.Parse(vt.url); err != nil {
t.Errorf("cannot parse url: %v", err)
continue
}
if err := cc.Write(&req); err != nil {
t.Errorf("writing request: %v", err)
continue
}
r, err := cc.Read(&req)
if err != nil {
t.Errorf("reading response: %v", err)
continue
}
switch r.StatusCode {
case StatusOK:
s := r.Header.Get("Result")
if s != vt.expected {
t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
}
case StatusMovedPermanently:
s := r.Header.Get("Location")
if s != vt.expected {
t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
}
default:
t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode)
}
}
}
var serveMuxRegister = []struct {
pattern string
h Handler
}{
{"/dir/", serve(200)},
{"/search", serve(201)},
{"codesearch.google.com/search", serve(202)},
{"codesearch.google.com/", serve(203)},
{"example.com/", HandlerFunc(checkQueryStringHandler)},
}
// serve returns a handler that sends a response with the given code.
func serve(code int) HandlerFunc {
return func(w ResponseWriter, r *Request) {
w.WriteHeader(code)
}
}
// checkQueryStringHandler checks if r.URL.RawQuery has the same value
// as the URL excluding the scheme and the query string and sends 200
// response code if it is, 500 otherwise.
func checkQueryStringHandler(w ResponseWriter, r *Request) {
u := *r.URL
u.Scheme = "http"
u.Host = r.Host
u.RawQuery = ""
if "http://"+r.URL.RawQuery == u.String() {
w.WriteHeader(200)
} else {
w.WriteHeader(500)
}
}
var serveMuxTests = []struct {
method string
host string
path string
code int
pattern string
}{
{"GET", "google.com", "/", 404, ""},
{"GET", "google.com", "/dir", 301, "/dir/"},
{"GET", "google.com", "/dir/", 200, "/dir/"},
{"GET", "google.com", "/dir/file", 200, "/dir/"},
{"GET", "google.com", "/search", 201, "/search"},
{"GET", "google.com", "/search/", 404, ""},
{"GET", "google.com", "/search/foo", 404, ""},
{"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"},
{"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"},
{"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"},
{"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"},
{"GET", "codesearch.google.com:443", "/", 203, "codesearch.google.com/"},
{"GET", "images.google.com", "/search", 201, "/search"},
{"GET", "images.google.com", "/search/", 404, ""},
{"GET", "images.google.com", "/search/foo", 404, ""},
{"GET", "google.com", "/../search", 301, "/search"},
{"GET", "google.com", "/dir/..", 301, ""},
{"GET", "google.com", "/dir/..", 301, ""},
{"GET", "google.com", "/dir/./file", 301, "/dir/"},
// The /foo -> /foo/ redirect applies to CONNECT requests
// but the path canonicalization does not.
{"CONNECT", "google.com", "/dir", 301, "/dir/"},
{"CONNECT", "google.com", "/../search", 404, ""},
{"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
{"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
{"CONNECT", "google.com", "/dir/./file", 200, "/dir/"},
}
func TestServeMuxHandler(t *testing.T) {
setParallel(t)
mux := NewServeMux()
for _, e := range serveMuxRegister {
mux.Handle(e.pattern, e.h)
}
for _, tt := range serveMuxTests {
r := &Request{
Method: tt.method,
Host: tt.host,
URL: &url.URL{
Path: tt.path,
},
}
h, pattern := mux.Handler(r)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, r)
if pattern != tt.pattern || rr.Code != tt.code {
t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern)
}
}
}
// Issue 24297
func TestServeMuxHandleFuncWithNilHandler(t *testing.T) {
setParallel(t)
defer func() {
if err := recover(); err == nil {
t.Error("expected call to mux.HandleFunc to panic")
}
}()
mux := NewServeMux()
mux.HandleFunc("/", nil)
}
var serveMuxTests2 = []struct {
method string
host string
url string
code int
redirOk bool
}{
{"GET", "google.com", "/", 404, false},
{"GET", "example.com", "/test/?example.com/test/", 200, false},
{"GET", "example.com", "test/?example.com/test/", 200, true},
}
// TestServeMuxHandlerRedirects tests that automatic redirects generated by
// mux.Handler() shouldn't clear the request's query string.
func TestServeMuxHandlerRedirects(t *testing.T) {
setParallel(t)
mux := NewServeMux()
for _, e := range serveMuxRegister {
mux.Handle(e.pattern, e.h)
}
for _, tt := range serveMuxTests2 {
tries := 1 // expect at most 1 redirection if redirOk is true.
turl := tt.url
for {
u, e := url.Parse(turl)
if e != nil {
t.Fatal(e)
}
r := &Request{
Method: tt.method,
Host: tt.host,
URL: u,
}
h, _ := mux.Handler(r)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, r)
if rr.Code != 301 {
if rr.Code != tt.code {
t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code)
}
break
}
if !tt.redirOk {
t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url)
break
}
turl = rr.HeaderMap.Get("Location")
tries--
}
if tries < 0 {
t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url)
}
}
}
// Tests for https://golang.org/issue/900
func TestMuxRedirectLeadingSlashes(t *testing.T) {
setParallel(t)
paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"}
for _, path := range paths {
req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
if err != nil {
t.Errorf("%s", err)
}
mux := NewServeMux()
resp := httptest.NewRecorder()
mux.ServeHTTP(resp, req)
if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected {
t.Errorf("Expected Location header set to %q; got %q", expected, loc)
return
}
if code, expected := resp.Code, StatusMovedPermanently; code != expected {
t.Errorf("Expected response code of StatusMovedPermanently; got %d", code)
return
}
}
}
// Test that the special cased "/route" redirect
// implicitly created by a registered "/route/"
// properly sets the query string in the redirect URL.
// See Issue 17841.
func TestServeWithSlashRedirectKeepsQueryString(t *testing.T) {
setParallel(t)
defer afterTest(t)
writeBackQuery := func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "%s", r.URL.RawQuery)
}
mux := NewServeMux()
mux.HandleFunc("/testOne", writeBackQuery)
mux.HandleFunc("/testTwo/", writeBackQuery)
mux.HandleFunc("/testThree", writeBackQuery)
mux.HandleFunc("/testThree/", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "%s:bar", r.URL.RawQuery)
})
ts := httptest.NewServer(mux)
defer ts.Close()
tests := [...]struct {
path string
method string
want string
statusOk bool
}{
0: {"/testOne?this=that", "GET", "this=that", true},
1: {"/testTwo?foo=bar", "GET", "foo=bar", true},
2: {"/testTwo?a=1&b=2&a=3", "GET", "a=1&b=2&a=3", true},
3: {"/testTwo?", "GET", "", true},
4: {"/testThree?foo", "GET", "foo", true},
5: {"/testThree/?foo", "GET", "foo:bar", true},
6: {"/testThree?foo", "CONNECT", "foo", true},
7: {"/testThree/?foo", "CONNECT", "foo:bar", true},
// canonicalization or not
8: {"/testOne/foo/..?foo", "GET", "foo", true},
9: {"/testOne/foo/..?foo", "CONNECT", "404 page not found\n", false},
}
for i, tt := range tests {
req, _ := NewRequest(tt.method, ts.URL+tt.path, nil)
res, err := ts.Client().Do(req)
if err != nil {
continue
}
slurp, _ := io.ReadAll(res.Body)
res.Body.Close()
if !tt.statusOk {
if got, want := res.StatusCode, 404; got != want {
t.Errorf("#%d: Status = %d; want = %d", i, got, want)
}
}
if got, want := string(slurp), tt.want; got != want {
t.Errorf("#%d: Body = %q; want = %q", i, got, want)
}
}
}
func TestServeWithSlashRedirectForHostPatterns(t *testing.T) {
setParallel(t)
defer afterTest(t)
mux := NewServeMux()
mux.Handle("example.com/pkg/foo/", stringHandler("example.com/pkg/foo/"))
mux.Handle("example.com/pkg/bar", stringHandler("example.com/pkg/bar"))
mux.Handle("example.com/pkg/bar/", stringHandler("example.com/pkg/bar/"))
mux.Handle("example.com:3000/pkg/connect/", stringHandler("example.com:3000/pkg/connect/"))
mux.Handle("example.com:9000/", stringHandler("example.com:9000/"))
mux.Handle("/pkg/baz/", stringHandler("/pkg/baz/"))
tests := []struct {
method string
url string
code int
loc string
want string
}{
{"GET", "http://example.com/", 404, "", ""},
{"GET", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""},
{"GET", "http://example.com/pkg/bar", 200, "", "example.com/pkg/bar"},
{"GET", "http://example.com/pkg/bar/", 200, "", "example.com/pkg/bar/"},
{"GET", "http://example.com/pkg/baz", 301, "/pkg/baz/", ""},
{"GET", "http://example.com:3000/pkg/foo", 301, "/pkg/foo/", ""},
{"CONNECT", "http://example.com/", 404, "", ""},
{"CONNECT", "http://example.com:3000/", 404, "", ""},
{"CONNECT", "http://example.com:9000/", 200, "", "example.com:9000/"},
{"CONNECT", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""},
{"CONNECT", "http://example.com:3000/pkg/foo", 404, "", ""},
{"CONNECT", "http://example.com:3000/pkg/baz", 301, "/pkg/baz/", ""},
{"CONNECT", "http://example.com:3000/pkg/connect", 301, "/pkg/connect/", ""},
}
ts := httptest.NewServer(mux)
defer ts.Close()
for i, tt := range tests {
req, _ := NewRequest(tt.method, tt.url, nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if got, want := w.Code, tt.code; got != want {
t.Errorf("#%d: Status = %d; want = %d", i, got, want)
}
if tt.code == 301 {
if got, want := w.HeaderMap.Get("Location"), tt.loc; got != want {
t.Errorf("#%d: Location = %q; want = %q", i, got, want)
}
} else {
if got, want := w.HeaderMap.Get("Result"), tt.want; got != want {
t.Errorf("#%d: Result = %q; want = %q", i, got, want)
}
}
}
}
func TestShouldRedirectConcurrency(t *testing.T) {
setParallel(t)
defer afterTest(t)
mux := NewServeMux()
ts := httptest.NewServer(mux)
defer ts.Close()
mux.HandleFunc("/", func(w ResponseWriter, r *Request) {})
}
func BenchmarkServeMux(b *testing.B) { benchmarkServeMux(b, true) }
func BenchmarkServeMux_SkipServe(b *testing.B) { benchmarkServeMux(b, false) }
func benchmarkServeMux(b *testing.B, runHandler bool) {
type test struct {
path string
code int
req *Request
}
// Build example handlers and requests
var tests []test
endpoints := []string{"search", "dir", "file", "change", "count", "s"}
for _, e := range endpoints {
for i := 200; i < 230; i++ {
p := fmt.Sprintf("/%s/%d/", e, i)
tests = append(tests, test{
path: p,
code: i,
req: &Request{Method: "GET", Host: "localhost", URL: &url.URL{Path: p}},
})
}
}
mux := NewServeMux()
for _, tt := range tests {
mux.Handle(tt.path, serve(tt.code))
}
rw := httptest.NewRecorder()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, tt := range tests {
*rw = httptest.ResponseRecorder{}
h, pattern := mux.Handler(tt.req)
if runHandler {
h.ServeHTTP(rw, tt.req)
if pattern != tt.path || rw.Code != tt.code {
b.Fatalf("got %d, %q, want %d, %q", rw.Code, pattern, tt.code, tt.path)
}
}
}
}
}
func TestServerTimeouts(t *testing.T) {
setParallel(t)
defer afterTest(t)
// Try three times, with increasing timeouts.
tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second}
for i, timeout := range tries {
err := testServerTimeouts(timeout)
if err == nil {
return
}
t.Logf("failed at %v: %v", timeout, err)
if i != len(tries)-1 {
t.Logf("retrying at %v ...", tries[i+1])
}
}
t.Fatal("all attempts failed")
}
func testServerTimeouts(timeout time.Duration) error {
reqNum := 0
ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
reqNum++
fmt.Fprintf(res, "req=%d", reqNum)
}))
ts.Config.ReadTimeout = timeout
ts.Config.WriteTimeout = timeout
ts.Start()
defer ts.Close()
// Hit the HTTP server successfully.
c := ts.Client()
r, err := c.Get(ts.URL)
if err != nil {
return fmt.Errorf("http Get #1: %v", err)
}
got, err := io.ReadAll(r.Body)
expected := "req=1"
if string(got) != expected || err != nil {
return fmt.Errorf("Unexpected response for request #1; got %q ,%v; expected %q, nil",
string(got), err, expected)
}
// Slow client that should timeout.
t1 := time.Now()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
return fmt.Errorf("Dial: %v", err)
}
buf := make([]byte, 1)
n, err := conn.Read(buf)
conn.Close()
latency := time.Since(t1)
if n != 0 || err != io.EOF {
return fmt.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF)
}
minLatency := timeout / 5 * 4
if latency < minLatency {
return fmt.Errorf("got EOF after %s, want >= %s", latency, minLatency)
}
// Hit the HTTP server successfully again, verifying that the
// previous slow connection didn't run our handler. (that we
// get "req=2", not "req=3")
r, err = c.Get(ts.URL)
if err != nil {
return fmt.Errorf("http Get #2: %v", err)
}
got, err = io.ReadAll(r.Body)
r.Body.Close()
expected = "req=2"
if string(got) != expected || err != nil {
return fmt.Errorf("Get #2 got %q, %v, want %q, nil", string(got), err, expected)
}
if !testing.Short() {
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
return fmt.Errorf("long Dial: %v", err)
}
defer conn.Close()
go io.Copy(io.Discard, conn)
for i := 0; i < 5; i++ {
_, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
if err != nil {
return fmt.Errorf("on write %d: %v", i, err)
}
time.Sleep(timeout / 2)
}
}
return nil
}
// Test that the HTTP/2 server handles Server.WriteTimeout (Issue 18437)
func TestHTTP2WriteDeadlineExtendedOnNewRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {}))
ts.Config.WriteTimeout = 250 * time.Millisecond
ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
ts.StartTLS()
defer ts.Close()
c := ts.Client()
if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
t.Fatal(err)
}
for i := 1; i <= 3; i++ {
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatal(err)
}
// fail test if no response after 1 second
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
req = req.WithContext(ctx)
r, err := c.Do(req)
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("http2 Get #%d response timed out", i)
}
if err != nil {
t.Fatalf("http2 Get #%d: %v", i, err)
}
r.Body.Close()
if r.ProtoMajor != 2 {
t.Fatalf("http2 Get expected HTTP/2.0, got %q", r.Proto)
}
time.Sleep(ts.Config.WriteTimeout / 2)
}
}
// tryTimeouts runs testFunc with increasing timeouts. Test passes on first success,
// and fails if all timeouts fail.
func tryTimeouts(t *testing.T, testFunc func(timeout time.Duration) error) {
tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second}
for i, timeout := range tries {
err := testFunc(timeout)
if err == nil {
return
}
t.Logf("failed at %v: %v", timeout, err)
if i != len(tries)-1 {
t.Logf("retrying at %v ...", tries[i+1])
}
}
t.Fatal("all attempts failed")
}
// Test that the HTTP/2 server RSTs stream on slow write.
func TestHTTP2WriteDeadlineEnforcedPerStream(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
tryTimeouts(t, testHTTP2WriteDeadlineEnforcedPerStream)
}
func testHTTP2WriteDeadlineEnforcedPerStream(timeout time.Duration) error {
reqNum := 0
ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
reqNum++
if reqNum == 1 {
return // first request succeeds
}
time.Sleep(timeout) // second request times out
}))
ts.Config.WriteTimeout = timeout / 2
ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
ts.StartTLS()
defer ts.Close()
c := ts.Client()
if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
return fmt.Errorf("ExportHttp2ConfigureTransport: %v", err)
}
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
return fmt.Errorf("NewRequest: %v", err)
}
r, err := c.Do(req)
if err != nil {
return fmt.Errorf("http2 Get #1: %v", err)
}
r.Body.Close()
if r.ProtoMajor != 2 {
return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
}
req, err = NewRequest("GET", ts.URL, nil)
if err != nil {
return fmt.Errorf("NewRequest: %v", err)
}
r, err = c.Do(req)
if err == nil {
r.Body.Close()
if r.ProtoMajor != 2 {
return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
}
return fmt.Errorf("http2 Get #2 expected error, got nil")
}
expected := "stream ID 3; INTERNAL_ERROR" // client IDs are odd, second stream should be 3
if !strings.Contains(err.Error(), expected) {
return fmt.Errorf("http2 Get #2: expected error to contain %q, got %q", expected, err)
}
return nil
}
// Test that the HTTP/2 server does not send RST when WriteDeadline not set.
func TestHTTP2NoWriteDeadline(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
tryTimeouts(t, testHTTP2NoWriteDeadline)
}
func testHTTP2NoWriteDeadline(timeout time.Duration) error {
reqNum := 0
ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
reqNum++
if reqNum == 1 {
return // first request succeeds
}
time.Sleep(timeout) // second request timesout
}))
ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
ts.StartTLS()
defer ts.Close()
c := ts.Client()
if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
return fmt.Errorf("ExportHttp2ConfigureTransport: %v", err)
}
for i := 0; i < 2; i++ {
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
return fmt.Errorf("NewRequest: %v", err)
}
r, err := c.Do(req)
if err != nil {
return fmt.Errorf("http2 Get #%d: %v", i, err)
}
r.Body.Close()
if r.ProtoMajor != 2 {
return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
}
}
return nil
}
// golang.org/issue/4741 -- setting only a write timeout that triggers
// shouldn't cause a handler to block forever on reads (next HTTP
// request) that will never happen.
func TestOnlyWriteTimeout(t *testing.T) {
setParallel(t)
defer afterTest(t)
var (
mu sync.RWMutex
conn net.Conn
)
var afterTimeoutErrc = make(chan error, 1)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) {
buf := make([]byte, 512<<10)
_, err := w.Write(buf)
if err != nil {
t.Errorf("handler Write error: %v", err)
return
}
mu.RLock()
defer mu.RUnlock()
if conn == nil {
t.Error("no established connection found")
return
}
conn.SetWriteDeadline(time.Now().Add(-30 * time.Second))
_, err = w.Write(buf)
afterTimeoutErrc <- err
}))
ts.Listener = trackLastConnListener{ts.Listener, &mu, &conn}
ts.Start()
defer ts.Close()
c := ts.Client()
errc := make(chan error, 1)
go func() {
res, err := c.Get(ts.URL)
if err != nil {
errc <- err
return
}
_, err = io.Copy(io.Discard, res.Body)
res.Body.Close()
errc <- err
}()
select {
case err := <-errc:
if err == nil {
t.Errorf("expected an error from Get request")
}
case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for Get error")
}
if err := <-afterTimeoutErrc; err == nil {
t.Error("expected write error after timeout")
}
}
// trackLastConnListener tracks the last net.Conn that was accepted.
type trackLastConnListener struct {
net.Listener
mu *sync.RWMutex
last *net.Conn // destination
}
func (l trackLastConnListener) Accept() (c net.Conn, err error) {
c, err = l.Listener.Accept()
if err == nil {
l.mu.Lock()
*l.last = c
l.mu.Unlock()
}
return
}
// TestIdentityResponse verifies that a handler can unset
func TestIdentityResponse(t *testing.T) {
setParallel(t)
defer afterTest(t)
handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
rw.Header().Set("Content-Length", "3")
rw.Header().Set("Transfer-Encoding", req.FormValue("te"))
switch {
case req.FormValue("overwrite") == "1":
_, err := rw.Write([]byte("foo TOO LONG"))
if err != ErrContentLength {
t.Errorf("expected ErrContentLength; got %v", err)
}
case req.FormValue("underwrite") == "1":
rw.Header().Set("Content-Length", "500")
rw.Write([]byte("too short"))
default:
rw.Write([]byte("foo"))
}
})
ts := httptest.NewServer(handler)
defer ts.Close()
c := ts.Client()
// Note: this relies on the assumption (which is true) that
// Get sends HTTP/1.1 or greater requests. Otherwise the
// server wouldn't have the choice to send back chunked
// responses.
for _, te := range []string{"", "identity"} {
url := ts.URL + "/?te=" + te
res, err := c.Get(url)
if err != nil {
t.Fatalf("error with Get of %s: %v", url, err)
}
if cl, expected := res.ContentLength, int64(3); cl != expected {
t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl)
}
if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected {
t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl)
}
if tl, expected := len(res.TransferEncoding), 0; tl != expected {
t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)",
url, expected, tl, res.TransferEncoding)
}
res.Body.Close()
}
// Verify that ErrContentLength is returned
url := ts.URL + "/?overwrite=1"
res, err := c.Get(url)
if err != nil {
t.Fatalf("error with Get of %s: %v", url, err)
}
res.Body.Close()
// Verify that the connection is closed when the declared Content-Length
// is larger than what the handler wrote.
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("error dialing: %v", err)
}
_, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n"))
if err != nil {
t.Fatalf("error writing: %v", err)
}
// The ReadAll will hang for a failing test.
got, _ := io.ReadAll(conn)
expectedSuffix := "\r\n\r\ntoo short"
if !strings.HasSuffix(string(got), expectedSuffix) {
t.Errorf("Expected output to end with %q; got response body %q",
expectedSuffix, string(got))
}
}
func testTCPConnectionCloses(t *testing.T, req string, h Handler) {
setParallel(t)
defer afterTest(t)
s := httptest.NewServer(h)
defer s.Close()
conn, err := net.Dial("tcp", s.Listener.Addr().String())
if err != nil {
t.Fatal("dial error:", err)
}
defer conn.Close()
_, err = fmt.Fprint(conn, req)
if err != nil {
t.Fatal("print error:", err)
}
r := bufio.NewReader(conn)
res, err := ReadResponse(r, &Request{Method: "GET"})
if err != nil {
t.Fatal("ReadResponse error:", err)
}
didReadAll := make(chan bool, 1)
go func() {
select {
case <-time.After(5 * time.Second):
t.Error("body not closed after 5s")
return
case <-didReadAll:
}
}()
_, err = io.ReadAll(r)
if err != nil {
t.Fatal("read error:", err)
}
didReadAll <- true
if !res.Close {
t.Errorf("Response.Close = false; want true")
}
}
func testTCPConnectionStaysOpen(t *testing.T, req string, handler Handler) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewServer(handler)
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
br := bufio.NewReader(conn)
for i := 0; i < 2; i++ {
if _, err := io.WriteString(conn, req); err != nil {
t.Fatal(err)
}
res, err := ReadResponse(br, nil)
if err != nil {
t.Fatalf("res %d: %v", i+1, err)
}
if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatalf("res %d body copy: %v", i+1, err)
}
res.Body.Close()
}
}
// TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive.
func TestServeHTTP10Close(t *testing.T) {
testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
ServeFile(w, r, "testdata/file")
}))
}
// TestClientCanClose verifies that clients can also force a connection to close.
func TestClientCanClose(t *testing.T) {
testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
// Nothing.
}))
}
// TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close,
// even for HTTP/1.1 requests.
func TestHandlersCanSetConnectionClose11(t *testing.T) {
testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Connection", "close")
}))
}
func TestHandlersCanSetConnectionClose10(t *testing.T) {
testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Connection", "close")
}))
}
func TestHTTP2UpgradeClosesConnection(t *testing.T) {
testTCPConnectionCloses(t, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
// Nothing. (if not hijacked, the server should close the connection
// afterwards)
}))
}
func send204(w ResponseWriter, r *Request) { w.WriteHeader(204) }
func send304(w ResponseWriter, r *Request) { w.WriteHeader(304) }
// Issue 15647: 204 responses can't have bodies, so HTTP/1.0 keep-alive conns should stay open.
func TestHTTP10KeepAlive204Response(t *testing.T) {
testTCPConnectionStaysOpen(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(send204))
}
func TestHTTP11KeepAlive204Response(t *testing.T) {
testTCPConnectionStaysOpen(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n", HandlerFunc(send204))
}
func TestHTTP10KeepAlive304Response(t *testing.T) {
testTCPConnectionStaysOpen(t,
"GET / HTTP/1.0\r\nConnection: keep-alive\r\nIf-Modified-Since: Mon, 02 Jan 2006 15:04:05 GMT\r\n\r\n",
HandlerFunc(send304))
}
// Issue 15703
func TestKeepAliveFinalChunkWithEOF(t *testing.T) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, false /* h1 */, HandlerFunc(func(w ResponseWriter, r *Request) {
w.(Flusher).Flush() // force chunked encoding
w.Write([]byte("{\"Addr\": \"" + r.RemoteAddr + "\"}"))
}))
defer cst.close()
type data struct {
Addr string
}
var addrs [2]data
for i := range addrs {
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatal(err)
}
if err := json.NewDecoder(res.Body).Decode(&addrs[i]); err != nil {
t.Fatal(err)
}
if addrs[i].Addr == "" {
t.Fatal("no address")
}
res.Body.Close()
}
if addrs[0] != addrs[1] {
t.Fatalf("connection not reused")
}
}
func TestSetsRemoteAddr_h1(t *testing.T) { testSetsRemoteAddr(t, h1Mode) }
func TestSetsRemoteAddr_h2(t *testing.T) { testSetsRemoteAddr(t, h2Mode) }
func testSetsRemoteAddr(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "%s", r.RemoteAddr)
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatalf("Get error: %v", err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Fatalf("ReadAll error: %v", err)
}
ip := string(body)
if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") {
t.Fatalf("Expected local addr; got %q", ip)
}
}
type blockingRemoteAddrListener struct {
net.Listener
conns chan<- net.Conn
}
func (l *blockingRemoteAddrListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
brac := &blockingRemoteAddrConn{
Conn: c,
addrs: make(chan net.Addr, 1),
}
l.conns <- brac
return brac, nil
}
type blockingRemoteAddrConn struct {
net.Conn
addrs chan net.Addr
}
func (c *blockingRemoteAddrConn) RemoteAddr() net.Addr {
return <-c.addrs
}
// Issue 12943
func TestServerAllowsBlockingRemoteAddr(t *testing.T) {
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "RA:%s", r.RemoteAddr)
}))
conns := make(chan net.Conn)
ts.Listener = &blockingRemoteAddrListener{
Listener: ts.Listener,
conns: conns,
}
ts.Start()
defer ts.Close()
c := ts.Client()
c.Timeout = time.Second
// Force separate connection for each:
c.Transport.(*Transport).DisableKeepAlives = true
fetch := func(num int, response chan<- string) {
resp, err := c.Get(ts.URL)
if err != nil {
t.Errorf("Request %d: %v", num, err)
response <- ""
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Request %d: %v", num, err)
response <- ""
return
}
response <- string(body)
}
// Start a request. The server will block on getting conn.RemoteAddr.
response1c := make(chan string, 1)
go fetch(1, response1c)
// Wait for the server to accept it; grab the connection.
conn1 := <-conns
// Start another request and grab its connection
response2c := make(chan string, 1)
go fetch(2, response2c)
var conn2 net.Conn
select {
case conn2 = <-conns:
case <-time.After(time.Second):
t.Fatal("Second Accept didn't happen")
}
// Send a response on connection 2.
conn2.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{
IP: net.ParseIP("12.12.12.12"), Port: 12}
// ... and see it
response2 := <-response2c
if g, e := response2, "RA:12.12.12.12:12"; g != e {
t.Fatalf("response 2 addr = %q; want %q", g, e)
}
// Finish the first response.
conn1.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{
IP: net.ParseIP("21.21.21.21"), Port: 21}
// ... and see it
response1 := <-response1c
if g, e := response1, "RA:21.21.21.21:21"; g != e {
t.Fatalf("response 1 addr = %q; want %q", g, e)
}
}
// TestHeadResponses verifies that all MIME type sniffing and Content-Length
// counting of GET requests also happens on HEAD requests.
func TestHeadResponses_h1(t *testing.T) { testHeadResponses(t, h1Mode) }
func TestHeadResponses_h2(t *testing.T) { testHeadResponses(t, h2Mode) }
func testHeadResponses(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
_, err := w.Write([]byte("<html>"))
if err != nil {
t.Errorf("ResponseWriter.Write: %v", err)
}
// Also exercise the ReaderFrom path
_, err = io.Copy(w, strings.NewReader("789a"))
if err != nil {
t.Errorf("Copy(ResponseWriter, ...): %v", err)
}
}))
defer cst.close()
res, err := cst.c.Head(cst.ts.URL)
if err != nil {
t.Error(err)
}
if len(res.TransferEncoding) > 0 {
t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
}
if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct)
}
if v := res.ContentLength; v != 10 {
t.Errorf("Content-Length: %d; want 10", v)
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
if len(body) > 0 {
t.Errorf("got unexpected body %q", string(body))
}
}
func TestTLSHandshakeTimeout(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
errc := make(chanWriter, 10) // but only expecting 1
ts.Config.ReadTimeout = 250 * time.Millisecond
ts.Config.ErrorLog = log.New(errc, "", 0)
ts.StartTLS()
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer conn.Close()
var buf [1]byte
n, err := conn.Read(buf[:])
if err == nil || n != 0 {
t.Errorf("Read = %d, %v; want an error and no bytes", n, err)
}
select {
case v := <-errc:
if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") {
t.Errorf("expected a TLS handshake timeout error; got %q", v)
}
case <-time.After(5 * time.Second):
t.Errorf("timeout waiting for logged error")
}
}
func TestTLSServer(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
if r.TLS != nil {
w.Header().Set("X-TLS-Set", "true")
if r.TLS.HandshakeComplete {
w.Header().Set("X-TLS-HandshakeComplete", "true")
}
}
}))
ts.Config.ErrorLog = log.New(io.Discard, "", 0)
defer ts.Close()
// Connect an idle TCP connection to this server before we run
// our real tests. This idle connection used to block forever
// in the TLS handshake, preventing future connections from
// being accepted. It may prevent future accidental blocking
// in newConn.
idleConn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer idleConn.Close()
if !strings.HasPrefix(ts.URL, "https://") {
t.Errorf("expected test TLS server to start with https://, got %q", ts.URL)
return
}
client := ts.Client()
res, err := client.Get(ts.URL)
if err != nil {
t.Error(err)
return
}
if res == nil {
t.Errorf("got nil Response")
return
}
defer res.Body.Close()
if res.Header.Get("X-TLS-Set") != "true" {
t.Errorf("expected X-TLS-Set response header")
return
}
if res.Header.Get("X-TLS-HandshakeComplete") != "true" {
t.Errorf("expected X-TLS-HandshakeComplete header")
}
}
func TestServeTLS(t *testing.T) {
CondSkipHTTP2(t)
// Not parallel: uses global test hooks.
defer afterTest(t)
defer SetTestHookServerServe(nil)
cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
if err != nil {
t.Fatal(err)
}
tlsConf := &tls.Config{
Certificates: []tls.Certificate{cert},
}
ln := newLocalListener(t)
defer ln.Close()
addr := ln.Addr().String()
serving := make(chan bool, 1)
SetTestHookServerServe(func(s *Server, ln net.Listener) {
serving <- true
})
handler := HandlerFunc(func(w ResponseWriter, r *Request) {})
s := &Server{
Addr: addr,
TLSConfig: tlsConf,
Handler: handler,
}
errc := make(chan error, 1)
go func() { errc <- s.ServeTLS(ln, "", "") }()
select {
case err := <-errc:
t.Fatalf("ServeTLS: %v", err)
case <-serving:
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"h2", "http/1.1"},
})
if err != nil {
t.Fatal(err)
}
defer c.Close()
if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want {
t.Errorf("NegotiatedProtocol = %q; want %q", got, want)
}
if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want {
t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want)
}
}
// Test that the HTTPS server nicely rejects plaintext HTTP/1.x requests.
func TestTLSServerRejectHTTPRequests(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
t.Error("unexpected HTTPS request")
}))
var errBuf bytes.Buffer
ts.Config.ErrorLog = log.New(&errBuf, "", 0)
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
io.WriteString(conn, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
slurp, err := io.ReadAll(conn)
if err != nil {
t.Fatal(err)
}
const wantPrefix = "HTTP/1.0 400 Bad Request\r\n"
if !strings.HasPrefix(string(slurp), wantPrefix) {
t.Errorf("response = %q; wanted prefix %q", slurp, wantPrefix)
}
}
// Issue 15908
func TestAutomaticHTTP2_Serve_NoTLSConfig(t *testing.T) {
testAutomaticHTTP2_Serve(t, nil, true)
}
func TestAutomaticHTTP2_Serve_NonH2TLSConfig(t *testing.T) {
testAutomaticHTTP2_Serve(t, &tls.Config{}, false)
}
func TestAutomaticHTTP2_Serve_H2TLSConfig(t *testing.T) {
testAutomaticHTTP2_Serve(t, &tls.Config{NextProtos: []string{"h2"}}, true)
}
func testAutomaticHTTP2_Serve(t *testing.T, tlsConf *tls.Config, wantH2 bool) {
setParallel(t)
defer afterTest(t)
ln := newLocalListener(t)
ln.Close() // immediately (not a defer!)
var s Server
s.TLSConfig = tlsConf
if err := s.Serve(ln); err == nil {
t.Fatal("expected an error")
}
gotH2 := s.TLSNextProto["h2"] != nil
if gotH2 != wantH2 {
t.Errorf("http2 configured = %v; want %v", gotH2, wantH2)
}
}
func TestAutomaticHTTP2_Serve_WithTLSConfig(t *testing.T) {
setParallel(t)
defer afterTest(t)
ln := newLocalListener(t)
ln.Close() // immediately (not a defer!)
var s Server
// Set the TLSConfig. In reality, this would be the
// *tls.Config given to tls.NewListener.
s.TLSConfig = &tls.Config{
NextProtos: []string{"h2"},
}
if err := s.Serve(ln); err == nil {
t.Fatal("expected an error")
}
on := s.TLSNextProto["h2"] != nil
if !on {
t.Errorf("http2 wasn't automatically enabled")
}
}
func TestAutomaticHTTP2_ListenAndServe(t *testing.T) {
cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
if err != nil {
t.Fatal(err)
}
testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
Certificates: []tls.Certificate{cert},
})
}
func TestAutomaticHTTP2_ListenAndServe_GetCertificate(t *testing.T) {
cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
if err != nil {
t.Fatal(err)
}
testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return &cert, nil
},
})
}
func testAutomaticHTTP2_ListenAndServe(t *testing.T, tlsConf *tls.Config) {
CondSkipHTTP2(t)
// Not parallel: uses global test hooks.
defer afterTest(t)
defer SetTestHookServerServe(nil)
var ok bool
var s *Server
const maxTries = 5
var ln net.Listener
Try:
for try := 0; try < maxTries; try++ {
ln = newLocalListener(t)
addr := ln.Addr().String()
ln.Close()
t.Logf("Got %v", addr)
lnc := make(chan net.Listener, 1)
SetTestHookServerServe(func(s *Server, ln net.Listener) {
lnc <- ln
})
s = &Server{
Addr: addr,
TLSConfig: tlsConf,
}
errc := make(chan error, 1)
go func() { errc <- s.ListenAndServeTLS("", "") }()
select {
case err := <-errc:
t.Logf("On try #%v: %v", try+1, err)
continue
case ln = <-lnc:
ok = true
t.Logf("Listening on %v", ln.Addr().String())
break Try
}
}
if !ok {
t.Fatalf("Failed to start up after %d tries", maxTries)
}
defer ln.Close()
c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"h2", "http/1.1"},
})
if err != nil {
t.Fatal(err)
}
defer c.Close()
if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want {
t.Errorf("NegotiatedProtocol = %q; want %q", got, want)
}
if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want {
t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want)
}
}
type serverExpectTest struct {
contentLength int // of request body
chunked bool
expectation string // e.g. "100-continue"
readBody bool // whether handler should read the body (if false, sends StatusUnauthorized)
expectedResponse string // expected substring in first line of http response
}
func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest {
return serverExpectTest{
contentLength: contentLength,
expectation: expectation,
readBody: readBody,
expectedResponse: expectedResponse,
}
}
var serverExpectTests = []serverExpectTest{
// Normal 100-continues, case-insensitive.
expectTest(100, "100-continue", true, "100 Continue"),
expectTest(100, "100-cOntInUE", true, "100 Continue"),
// No 100-continue.
expectTest(100, "", true, "200 OK"),
// 100-continue but requesting client to deny us,
// so it never reads the body.
expectTest(100, "100-continue", false, "401 Unauthorized"),
// Likewise without 100-continue:
expectTest(100, "", false, "401 Unauthorized"),
// Non-standard expectations are failures
expectTest(0, "a-pony", false, "417 Expectation Failed"),
// Expect-100 requested but no body (is apparently okay: Issue 7625)
expectTest(0, "100-continue", true, "200 OK"),
// Expect-100 requested but handler doesn't read the body
expectTest(0, "100-continue", false, "401 Unauthorized"),
// Expect-100 continue with no body, but a chunked body.
{
expectation: "100-continue",
readBody: true,
chunked: true,
expectedResponse: "100 Continue",
},
}
// Tests that the server responds to the "Expect" request header
// correctly.
// http2 test: TestServer_Response_Automatic100Continue
func TestServerExpect(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
// Note using r.FormValue("readbody") because for POST
// requests that would read from r.Body, which we only
// conditionally want to do.
if strings.Contains(r.URL.RawQuery, "readbody=true") {
io.ReadAll(r.Body)
w.Write([]byte("Hi"))
} else {
w.WriteHeader(StatusUnauthorized)
}
}))
defer ts.Close()
runTest := func(test serverExpectTest) {
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer conn.Close()
// Only send the body immediately if we're acting like an HTTP client
// that doesn't send 100-continue expectations.
writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue"
go func() {
contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength)
if test.chunked {
contentLen = "Transfer-Encoding: chunked"
}
_, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+
"Connection: close\r\n"+
"%s\r\n"+
"Expect: %s\r\nHost: foo\r\n\r\n",
test.readBody, contentLen, test.expectation)
if err != nil {
t.Errorf("On test %#v, error writing request headers: %v", test, err)
return
}
if writeBody {
var targ io.WriteCloser = struct {
io.Writer
io.Closer
}{
conn,
io.NopCloser(nil),
}
if test.chunked {
targ = httputil.NewChunkedWriter(conn)
}
body := strings.Repeat("A", test.contentLength)
_, err = fmt.Fprint(targ, body)
if err == nil {
err = targ.Close()
}
if err != nil {
if !test.readBody {
// Server likely already hung up on us.
// See larger comment below.
t.Logf("On test %#v, acceptable error writing request body: %v", test, err)
return
}
t.Errorf("On test %#v, error writing request body: %v", test, err)
}
}
}()
bufr := bufio.NewReader(conn)
line, err := bufr.ReadString('\n')
if err != nil {
if writeBody && !test.readBody {
// This is an acceptable failure due to a possible TCP race:
// We were still writing data and the server hung up on us. A TCP
// implementation may send a RST if our request body data was known
// to be lost, which may trigger our reads to fail.
// See RFC 1122 page 88.
t.Logf("On test %#v, acceptable error from ReadString: %v", test, err)
return
}
t.Fatalf("On test %#v, ReadString: %v", test, err)
}
if !strings.Contains(line, test.expectedResponse) {
t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse)
}
}
for _, test := range serverExpectTests {
runTest(test)
}
}
// Under a ~256KB (maxPostHandlerReadBytes) threshold, the server
// should consume client request bodies that a handler didn't read.
func TestServerUnreadRequestBodyLittle(t *testing.T) {
setParallel(t)
defer afterTest(t)
conn := new(testConn)
body := strings.Repeat("x", 100<<10)
conn.readBuf.Write([]byte(fmt.Sprintf(
"POST / HTTP/1.1\r\n"+
"Host: test\r\n"+
"Content-Length: %d\r\n"+
"\r\n", len(body))))
conn.readBuf.Write([]byte(body))
done := make(chan bool)
readBufLen := func() int {
conn.readMu.Lock()
defer conn.readMu.Unlock()
return conn.readBuf.Len()
}
ls := &oneConnListener{conn}
go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
defer close(done)
if bufLen := readBufLen(); bufLen < len(body)/2 {
t.Errorf("on request, read buffer length is %d; expected about 100 KB", bufLen)
}
rw.WriteHeader(200)
rw.(Flusher).Flush()
if g, e := readBufLen(), 0; g != e {
t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e)
}
if c := rw.Header().Get("Connection"); c != "" {
t.Errorf(`Connection header = %q; want ""`, c)
}
}))
<-done
}
// Over a ~256KB (maxPostHandlerReadBytes) threshold, the server
// should ignore client request bodies that a handler didn't read
// and close the connection.
func TestServerUnreadRequestBodyLarge(t *testing.T) {
setParallel(t)
if testing.Short() && testenv.Builder() == "" {
t.Log("skipping in short mode")
}
conn := new(testConn)
body := strings.Repeat("x", 1<<20)
conn.readBuf.Write([]byte(fmt.Sprintf(
"POST / HTTP/1.1\r\n"+
"Host: test\r\n"+
"Content-Length: %d\r\n"+
"\r\n", len(body))))
conn.readBuf.Write([]byte(body))
conn.closec = make(chan bool, 1)
ls := &oneConnListener{conn}
go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
if conn.readBuf.Len() < len(body)/2 {
t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
}
rw.WriteHeader(200)
rw.(Flusher).Flush()
if conn.readBuf.Len() < len(body)/2 {
t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
}
}))
<-conn.closec
if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") {
t.Errorf("Expected a Connection: close header; got response: %s", res)
}
}
type handlerBodyCloseTest struct {
bodySize int
bodyChunked bool
reqConnClose bool
wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF?
wantNextReq bool // should it find the next request on the same conn?
}
func (t handlerBodyCloseTest) connectionHeader() string {
if t.reqConnClose {
return "Connection: close\r\n"
}
return ""
}
var handlerBodyCloseTests = [...]handlerBodyCloseTest{
// Small enough to slurp past to the next request +
// has Content-Length.
0: {
bodySize: 20 << 10,
bodyChunked: false,
reqConnClose: false,
wantEOFSearch: true,
wantNextReq: true,
},
// Small enough to slurp past to the next request +
// is chunked.
1: {
bodySize: 20 << 10,
bodyChunked: true,
reqConnClose: false,
wantEOFSearch: true,
wantNextReq: true,
},
// Small enough to slurp past to the next request +
// has Content-Length +
// declares Connection: close (so pointless to read more).
2: {
bodySize: 20 << 10,
bodyChunked: false,
reqConnClose: true,
wantEOFSearch: false,
wantNextReq: false,
},
// Small enough to slurp past to the next request +
// declares Connection: close,
// but chunked, so it might have trailers.
// TODO: maybe skip this search if no trailers were declared
// in the headers.
3: {
bodySize: 20 << 10,
bodyChunked: true,
reqConnClose: true,
wantEOFSearch: true,
wantNextReq: false,
},
// Big with Content-Length, so give up immediately if we know it's too big.
4: {
bodySize: 1 << 20,
bodyChunked: false, // has a Content-Length
reqConnClose: false,
wantEOFSearch: false,
wantNextReq: false,
},
// Big chunked, so read a bit before giving up.
5: {
bodySize: 1 << 20,
bodyChunked: true,
reqConnClose: false,
wantEOFSearch: true,
wantNextReq: false,
},
// Big with Connection: close, but chunked, so search for trailers.
// TODO: maybe skip this search if no trailers were declared
// in the headers.
6: {
bodySize: 1 << 20,
bodyChunked: true,
reqConnClose: true,
wantEOFSearch: true,
wantNextReq: false,
},
// Big with Connection: close, so don't do any reads on Close.
// With Content-Length.
7: {
bodySize: 1 << 20,
bodyChunked: false,
reqConnClose: true,
wantEOFSearch: false,
wantNextReq: false,
},
}
func TestHandlerBodyClose(t *testing.T) {
setParallel(t)
if testing.Short() && testenv.Builder() == "" {
t.Skip("skipping in -short mode")
}
for i, tt := range handlerBodyCloseTests {
testHandlerBodyClose(t, i, tt)
}
}
func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) {
conn := new(testConn)
body := strings.Repeat("x", tt.bodySize)
if tt.bodyChunked {
conn.readBuf.WriteString("POST / HTTP/1.1\r\n" +
"Host: test\r\n" +
tt.connectionHeader() +
"Transfer-Encoding: chunked\r\n" +
"\r\n")
cw := internal.NewChunkedWriter(&conn.readBuf)
io.WriteString(cw, body)
cw.Close()
conn.readBuf.WriteString("\r\n")
} else {
conn.readBuf.Write([]byte(fmt.Sprintf(
"POST / HTTP/1.1\r\n"+
"Host: test\r\n"+
tt.connectionHeader()+
"Content-Length: %d\r\n"+
"\r\n", len(body))))
conn.readBuf.Write([]byte(body))
}
if !tt.reqConnClose {
conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n")
}
conn.closec = make(chan bool, 1)
readBufLen := func() int {
conn.readMu.Lock()
defer conn.readMu.Unlock()
return conn.readBuf.Len()
}
ls := &oneConnListener{conn}
var numReqs int
var size0, size1 int
go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
numReqs++
if numReqs == 1 {
size0 = readBufLen()
req.Body.Close()
size1 = readBufLen()
}
}))
<-conn.closec
if numReqs < 1 || numReqs > 2 {
t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs)
}
didSearch := size0 != size1
if didSearch != tt.wantEOFSearch {
t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1)
}
if tt.wantNextReq && numReqs != 2 {
t.Errorf("%d. numReq = %d; want 2", i, numReqs)
}
}
// testHandlerBodyConsumer represents a function injected into a test handler to
// vary work done on a request Body.
type testHandlerBodyConsumer struct {
name string
f func(io.ReadCloser)
}
var testHandlerBodyConsumers = []testHandlerBodyConsumer{
{"nil", func(io.ReadCloser) {}},
{"close", func(r io.ReadCloser) { r.Close() }},
{"discard", func(r io.ReadCloser) { io.Copy(io.Discard, r) }},
}
func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
setParallel(t)
defer afterTest(t)
for _, handler := range testHandlerBodyConsumers {
conn := new(testConn)
conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
"Host: test\r\n" +
"Transfer-Encoding: chunked\r\n" +
"\r\n" +
"hax\r\n" + // Invalid chunked encoding
"GET /secret HTTP/1.1\r\n" +
"Host: test\r\n" +
"\r\n")
conn.closec = make(chan bool, 1)
ls := &oneConnListener{conn}
var numReqs int
go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) {
numReqs++
if strings.Contains(req.URL.Path, "secret") {
t.Error("Request for /secret encountered, should not have happened.")
}
handler.f(req.Body)
}))
<-conn.closec
if numReqs != 1 {
t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
}
}
}
func TestInvalidTrailerClosesConnection(t *testing.T) {
setParallel(t)
defer afterTest(t)
for _, handler := range testHandlerBodyConsumers {
conn := new(testConn)
conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
"Host: test\r\n" +
"Trailer: hack\r\n" +
"Transfer-Encoding: chunked\r\n" +
"\r\n" +
"3\r\n" +
"hax\r\n" +
"0\r\n" +
"I'm not a valid trailer\r\n" +
"GET /secret HTTP/1.1\r\n" +
"Host: test\r\n" +
"\r\n")
conn.closec = make(chan bool, 1)
ln := &oneConnListener{conn}
var numReqs int
go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) {
numReqs++
if strings.Contains(req.URL.Path, "secret") {
t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name)
}
handler.f(req.Body)
}))
<-conn.closec
if numReqs != 1 {
t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs)
}
}
}
// slowTestConn is a net.Conn that provides a means to simulate parts of a
// request being received piecemeal. Deadlines can be set and enforced in both
// Read and Write.
type slowTestConn struct {
// over multiple calls to Read, time.Durations are slept, strings are read.
script []interface{}
closec chan bool
mu sync.Mutex // guards rd/wd
rd, wd time.Time // read, write deadline
noopConn
}
func (c *slowTestConn) SetDeadline(t time.Time) error {
c.SetReadDeadline(t)
c.SetWriteDeadline(t)
return nil
}
func (c *slowTestConn) SetReadDeadline(t time.Time) error {
c.mu.Lock()
defer c.mu.Unlock()
c.rd = t
return nil
}
func (c *slowTestConn) SetWriteDeadline(t time.Time) error {
c.mu.Lock()
defer c.mu.Unlock()
c.wd = t
return nil
}
func (c *slowTestConn) Read(b []byte) (n int, err error) {
c.mu.Lock()
defer c.mu.Unlock()
restart:
if !c.rd.IsZero() && time.Now().After(c.rd) {
return 0, syscall.ETIMEDOUT
}
if len(c.script) == 0 {
return 0, io.EOF
}
switch cue := c.script[0].(type) {
case time.Duration:
if !c.rd.IsZero() {
// If the deadline falls in the middle of our sleep window, deduct
// part of the sleep, then return a timeout.
if remaining := time.Until(c.rd); remaining < cue {
c.script[0] = cue - remaining
time.Sleep(remaining)
return 0, syscall.ETIMEDOUT
}
}
c.script = c.script[1:]
time.Sleep(cue)
goto restart
case string:
n = copy(b, cue)
// If cue is too big for the buffer, leave the end for the next Read.
if len(cue) > n {
c.script[0] = cue[n:]
} else {
c.script = c.script[1:]
}
default:
panic("unknown cue in slowTestConn script")
}
return
}
func (c *slowTestConn) Close() error {
select {
case c.closec <- true:
default:
}
return nil
}
func (c *slowTestConn) Write(b []byte) (int, error) {
if !c.wd.IsZero() && time.Now().After(c.wd) {
return 0, syscall.ETIMEDOUT
}
return len(b), nil
}
func TestRequestBodyTimeoutClosesConnection(t *testing.T) {
if testing.Short() {
t.Skip("skipping in -short mode")
}
defer afterTest(t)
for _, handler := range testHandlerBodyConsumers {
conn := &slowTestConn{
script: []interface{}{
"POST /public HTTP/1.1\r\n" +
"Host: test\r\n" +
"Content-Length: 10000\r\n" +
"\r\n",
"foo bar baz",
600 * time.Millisecond, // Request deadline should hit here
"GET /secret HTTP/1.1\r\n" +
"Host: test\r\n" +
"\r\n",
},
closec: make(chan bool, 1),
}
ls := &oneConnListener{conn}
var numReqs int
s := Server{
Handler: HandlerFunc(func(_ ResponseWriter, req *Request) {
numReqs++
if strings.Contains(req.URL.Path, "secret") {
t.Error("Request for /secret encountered, should not have happened.")
}
handler.f(req.Body)
}),
ReadTimeout: 400 * time.Millisecond,
}
go s.Serve(ls)
<-conn.closec
if numReqs != 1 {
t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
}
}
}
func TestTimeoutHandler_h1(t *testing.T) { testTimeoutHandler(t, h1Mode) }
func TestTimeoutHandler_h2(t *testing.T) { testTimeoutHandler(t, h2Mode) }
func testTimeoutHandler(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
sendHi := make(chan bool, 1)
writeErrors := make(chan error, 1)
sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
<-sendHi
_, werr := w.Write([]byte("hi"))
writeErrors <- werr
})
timeout := make(chan time.Time, 1) // write to this to force timeouts
cst := newClientServerTest(t, h2, NewTestTimeoutHandler(sayHi, timeout))
defer cst.close()
// Succeed without timing out:
sendHi <- true
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Error(err)
}
if g, e := res.StatusCode, StatusOK; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
body, _ := io.ReadAll(res.Body)
if g, e := string(body), "hi"; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
if g := <-writeErrors; g != nil {
t.Errorf("got unexpected Write error on first request: %v", g)
}
// Times out:
timeout <- time.Time{}
res, err = cst.c.Get(cst.ts.URL)
if err != nil {
t.Error(err)
}
if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
body, _ = io.ReadAll(res.Body)
if !strings.Contains(string(body), "<title>Timeout</title>") {
t.Errorf("expected timeout body; got %q", string(body))
}
if g, w := res.Header.Get("Content-Type"), "text/html; charset=utf-8"; g != w {
t.Errorf("response content-type = %q; want %q", g, w)
}
// Now make the previously-timed out handler speak again,
// which verifies the panic is handled:
sendHi <- true
if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
t.Errorf("expected Write error of %v; got %v", e, g)
}
}
// See issues 8209 and 8414.
func TestTimeoutHandlerRace(t *testing.T) {
setParallel(t)
defer afterTest(t)
delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
ms, _ := strconv.Atoi(r.URL.Path[1:])
if ms == 0 {
ms = 1
}
for i := 0; i < ms; i++ {
w.Write([]byte("hi"))
time.Sleep(time.Millisecond)
}
})
ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
defer ts.Close()
c := ts.Client()
var wg sync.WaitGroup
gate := make(chan bool, 10)
n := 50
if testing.Short() {
n = 10
gate = make(chan bool, 3)
}
for i := 0; i < n; i++ {
gate <- true
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-gate }()
res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
if err == nil {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}
}()
}
wg.Wait()
}
// See issues 8209 and 8414.
// Both issues involved panics in the implementation of TimeoutHandler.
func TestTimeoutHandlerRaceHeader(t *testing.T) {
setParallel(t)
defer afterTest(t)
delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
w.WriteHeader(204)
})
ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
defer ts.Close()
var wg sync.WaitGroup
gate := make(chan bool, 50)
n := 500
if testing.Short() {
n = 10
}
c := ts.Client()
for i := 0; i < n; i++ {
gate <- true
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-gate }()
res, err := c.Get(ts.URL)
if err != nil {
// We see ECONNRESET from the connection occasionally,
// and that's OK: this test is checking that the server does not panic.
t.Log(err)
return
}
defer res.Body.Close()
io.Copy(io.Discard, res.Body)
}()
}
wg.Wait()
}
// Issue 9162
func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
setParallel(t)
defer afterTest(t)
sendHi := make(chan bool, 1)
writeErrors := make(chan error, 1)
sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/plain")
<-sendHi
_, werr := w.Write([]byte("hi"))
writeErrors <- werr
})
timeout := make(chan time.Time, 1) // write to this to force timeouts
cst := newClientServerTest(t, h1Mode, NewTestTimeoutHandler(sayHi, timeout))
defer cst.close()
// Succeed without timing out:
sendHi <- true
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Error(err)
}
if g, e := res.StatusCode, StatusOK; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
body, _ := io.ReadAll(res.Body)
if g, e := string(body), "hi"; g != e {
t.Errorf("got body %q; expected %q", g, e)
}
if g := <-writeErrors; g != nil {
t.Errorf("got unexpected Write error on first request: %v", g)
}
// Times out:
timeout <- time.Time{}
res, err = cst.c.Get(cst.ts.URL)
if err != nil {
t.Error(err)
}
if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
t.Errorf("got res.StatusCode %d; expected %d", g, e)
}
body, _ = io.ReadAll(res.Body)
if !strings.Contains(string(body), "<title>Timeout</title>") {
t.Errorf("expected timeout body; got %q", string(body))
}
// Now make the previously-timed out handler speak again,
// which verifies the panic is handled:
sendHi <- true
if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
t.Errorf("expected Write error of %v; got %v", e, g)
}
}
// Issue 14568.
func TestTimeoutHandlerStartTimerWhenServing(t *testing.T) {
if testing.Short() {
t.Skip("skipping sleeping test in -short mode")
}
defer afterTest(t)
var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
w.WriteHeader(StatusNoContent)
}
timeout := 300 * time.Millisecond
ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
defer ts.Close()
c := ts.Client()
// Issue was caused by the timeout handler starting the timer when
// was created, not when the request. So wait for more than the timeout
// to ensure that's not the case.
time.Sleep(2 * timeout)
res, err := c.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != StatusNoContent {
t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusNoContent)
}
}
// https://golang.org/issue/15948
func TestTimeoutHandlerEmptyResponse(t *testing.T) {
setParallel(t)
defer afterTest(t)
var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
// No response.
}
timeout := 300 * time.Millisecond
ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
defer ts.Close()
c := ts.Client()
res, err := c.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != StatusOK {
t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusOK)
}
}
// https://golang.org/issues/22084
func TestTimeoutHandlerPanicRecovery(t *testing.T) {
wrapper := func(h Handler) Handler {
return TimeoutHandler(h, time.Second, "")
}
testHandlerPanic(t, false, false, wrapper, "intentional death for testing")
}
func TestRedirectBadPath(t *testing.T) {
// This used to crash. It's not valid input (bad path), but it
// shouldn't crash.
rr := httptest.NewRecorder()
req := &Request{
Method: "GET",
URL: &url.URL{
Scheme: "http",
Path: "not-empty-but-no-leading-slash", // bogus
},
}
Redirect(rr, req, "", 304)
if rr.Code != 304 {
t.Errorf("Code = %d; want 304", rr.Code)
}
}
// Test different URL formats and schemes
func TestRedirect(t *testing.T) {
req, _ := NewRequest("GET", "http://example.com/qux/", nil)
var tests = []struct {
in string
want string
}{
// normal http
{"http://foobar.com/baz", "http://foobar.com/baz"},
// normal https
{"https://foobar.com/baz", "https://foobar.com/baz"},
// custom scheme
{"test://foobar.com/baz", "test://foobar.com/baz"},
// schemeless
{"//foobar.com/baz", "//foobar.com/baz"},
// relative to the root
{"/foobar.com/baz", "/foobar.com/baz"},
// relative to the current path
{"foobar.com/baz", "/qux/foobar.com/baz"},
// relative to the current path (+ going upwards)
{"../quux/foobar.com/baz", "/quux/foobar.com/baz"},
// incorrect number of slashes
{"///foobar.com/baz", "/foobar.com/baz"},
// Verifies we don't path.Clean() on the wrong parts in redirects:
{"/foo?next=http://bar.com/", "/foo?next=http://bar.com/"},
{"http://localhost:8080/_ah/login?continue=http://localhost:8080/",
"http://localhost:8080/_ah/login?continue=http://localhost:8080/"},
{"/фубар", "/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
{"http://foo.com/фубар", "http://foo.com/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
}
for _, tt := range tests {
rec := httptest.NewRecorder()
Redirect(rec, req, tt.in, 302)
if got, want := rec.Code, 302; got != want {
t.Errorf("Redirect(%q) generated status code %v; want %v", tt.in, got, want)
}
if got := rec.Header().Get("Location"); got != tt.want {
t.Errorf("Redirect(%q) generated Location header %q; want %q", tt.in, got, tt.want)
}
}
}
// Test that Redirect sets Content-Type header for GET and HEAD requests
// and writes a short HTML body, unless the request already has a Content-Type header.
func TestRedirectContentTypeAndBody(t *testing.T) {
type ctHeader struct {
Values []string
}
var tests = []struct {
method string
ct *ctHeader // Optional Content-Type header to set.
wantCT string
wantBody string
}{
{MethodGet, nil, "text/html; charset=utf-8", "<a href=\"/foo\">Found</a>.\n\n"},
{MethodHead, nil, "text/html; charset=utf-8", ""},
{MethodPost, nil, "", ""},
{MethodDelete, nil, "", ""},
{"foo", nil, "", ""},
{MethodGet, &ctHeader{[]string{"application/test"}}, "application/test", ""},
{MethodGet, &ctHeader{[]string{}}, "", ""},
{MethodGet, &ctHeader{nil}, "", ""},
}
for _, tt := range tests {
req := httptest.NewRequest(tt.method, "http://example.com/qux/", nil)
rec := httptest.NewRecorder()
if tt.ct != nil {
rec.Header()["Content-Type"] = tt.ct.Values
}
Redirect(rec, req, "/foo", 302)
if got, want := rec.Code, 302; got != want {
t.Errorf("Redirect(%q, %#v) generated status code %v; want %v", tt.method, tt.ct, got, want)
}
if got, want := rec.Header().Get("Content-Type"), tt.wantCT; got != want {
t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want)
}
resp := rec.Result()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := string(body), tt.wantBody; got != want {
t.Errorf("Redirect(%q, %#v) generated Body %q; want %q", tt.method, tt.ct, got, want)
}
}
}
// TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
// when there is no body (either because the method doesn't permit a body, or an
// explicit Content-Length of zero is present), then the transport can re-use the
// connection immediately. But when it re-uses the connection, it typically closes
// the previous request's body, which is not optimal for zero-lengthed bodies,
// as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
func TestZeroLengthPostAndResponse_h1(t *testing.T) {
testZeroLengthPostAndResponse(t, h1Mode)
}
func TestZeroLengthPostAndResponse_h2(t *testing.T) {
testZeroLengthPostAndResponse(t, h2Mode)
}
func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
all, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("handler ReadAll: %v", err)
}
if len(all) != 0 {
t.Errorf("handler got %d bytes; expected 0", len(all))
}
rw.Header().Set("Content-Length", "0")
}))
defer cst.close()
req, err := NewRequest("POST", cst.ts.URL, strings.NewReader(""))
if err != nil {
t.Fatal(err)
}
req.ContentLength = 0
var resp [5]*Response
for i := range resp {
resp[i], err = cst.c.Do(req)
if err != nil {
t.Fatalf("client post #%d: %v", i, err)
}
}
for i := range resp {
all, err := io.ReadAll(resp[i].Body)
if err != nil {
t.Fatalf("req #%d: client ReadAll: %v", i, err)
}
if len(all) != 0 {
t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
}
}
}
func TestHandlerPanicNil_h1(t *testing.T) { testHandlerPanic(t, false, h1Mode, nil, nil) }
func TestHandlerPanicNil_h2(t *testing.T) { testHandlerPanic(t, false, h2Mode, nil, nil) }
func TestHandlerPanic_h1(t *testing.T) {
testHandlerPanic(t, false, h1Mode, nil, "intentional death for testing")
}
func TestHandlerPanic_h2(t *testing.T) {
testHandlerPanic(t, false, h2Mode, nil, "intentional death for testing")
}
func TestHandlerPanicWithHijack(t *testing.T) {
// Only testing HTTP/1, and our http2 server doesn't support hijacking.
testHandlerPanic(t, true, h1Mode, nil, "intentional death for testing")
}
func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue interface{}) {
defer afterTest(t)
// Unlike the other tests that set the log output to io.Discard
// to quiet the output, this test uses a pipe. The pipe serves three
// purposes:
//
// 1) The log.Print from the http server (generated by the caught
// panic) will go to the pipe instead of stderr, making the
// output quiet.
//
// 2) We read from the pipe to verify that the handler
// actually caught the panic and logged something.
//
// 3) The blocking Read call prevents this TestHandlerPanic
// function from exiting before the HTTP server handler
// finishes crashing. If this text function exited too
// early (and its defer log.SetOutput(os.Stderr) ran),
// then the crash output could spill into the next test.
pr, pw := io.Pipe()
log.SetOutput(pw)
defer log.SetOutput(os.Stderr)
defer pw.Close()
var handler Handler = HandlerFunc(func(w ResponseWriter, r *Request) {
if withHijack {
rwc, _, err := w.(Hijacker).Hijack()
if err != nil {
t.Logf("unexpected error: %v", err)
}
defer rwc.Close()
}
panic(panicValue)
})
if wrapper != nil {
handler = wrapper(handler)
}
cst := newClientServerTest(t, h2, handler)
defer cst.close()
// Do a blocking read on the log output pipe so its logging
// doesn't bleed into the next test. But wait only 5 seconds
// for it.
done := make(chan bool, 1)
go func() {
buf := make([]byte, 4<<10)
_, err := pr.Read(buf)
pr.Close()
if err != nil && err != io.EOF {
t.Error(err)
}
done <- true
}()
_, err := cst.c.Get(cst.ts.URL)
if err == nil {
t.Logf("expected an error")
}
if panicValue == nil {
return
}
select {
case <-done:
return
case <-time.After(5 * time.Second):
t.Fatal("expected server handler to log an error")
}
}
type terrorWriter struct{ t *testing.T }
func (w terrorWriter) Write(p []byte) (int, error) {
w.t.Errorf("%s", p)
return len(p), nil
}
// Issue 16456: allow writing 0 bytes on hijacked conn to test hijack
// without any log spam.
func TestServerWriteHijackZeroBytes(t *testing.T) {
defer afterTest(t)
done := make(chan struct{})
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
defer close(done)
w.(Flusher).Flush()
conn, _, err := w.(Hijacker).Hijack()
if err != nil {
t.Errorf("Hijack: %v", err)
return
}
defer conn.Close()
_, err = w.Write(nil)
if err != ErrHijacked {
t.Errorf("Write error = %v; want ErrHijacked", err)
}
}))
ts.Config.ErrorLog = log.New(terrorWriter{t}, "Unexpected write: ", 0)
ts.Start()
defer ts.Close()
c := ts.Client()
res, err := c.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}
func TestServerNoDate_h1(t *testing.T) { testServerNoHeader(t, h1Mode, "Date") }
func TestServerNoDate_h2(t *testing.T) { testServerNoHeader(t, h2Mode, "Date") }
func TestServerNoContentType_h1(t *testing.T) { testServerNoHeader(t, h1Mode, "Content-Type") }
func TestServerNoContentType_h2(t *testing.T) { testServerNoHeader(t, h2Mode, "Content-Type") }
func testServerNoHeader(t *testing.T, h2 bool, header string) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header()[header] = nil
io.WriteString(w, "<html>foo</html>") // non-empty
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if got, ok := res.Header[header]; ok {
t.Fatalf("Expected no %s header; got %q", header, got)
}
}
func TestStripPrefix(t *testing.T) {
setParallel(t)
defer afterTest(t)
h := HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("X-Path", r.URL.Path)
w.Header().Set("X-RawPath", r.URL.RawPath)
})
ts := httptest.NewServer(StripPrefix("/foo/bar", h))
defer ts.Close()
c := ts.Client()
cases := []struct {
reqPath string
path string // If empty we want a 404.
rawPath string
}{
{"/foo/bar/qux", "/qux", ""},
{"/foo/bar%2Fqux", "/qux", "%2Fqux"},
{"/foo%2Fbar/qux", "", ""}, // Escaped prefix does not match.
{"/bar", "", ""}, // No prefix match.
}
for _, tc := range cases {
t.Run(tc.reqPath, func(t *testing.T) {
res, err := c.Get(ts.URL + tc.reqPath)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if tc.path == "" {
if res.StatusCode != StatusNotFound {
t.Errorf("got %q, want 404 Not Found", res.Status)
}
return
}
if res.StatusCode != StatusOK {
t.Fatalf("got %q, want 200 OK", res.Status)
}
if g, w := res.Header.Get("X-Path"), tc.path; g != w {
t.Errorf("got Path %q, want %q", g, w)
}
if g, w := res.Header.Get("X-RawPath"), tc.rawPath; g != w {
t.Errorf("got RawPath %q, want %q", g, w)
}
})
}
}
// https://golang.org/issue/18952.
func TestStripPrefixNotModifyRequest(t *testing.T) {
h := StripPrefix("/foo", NotFoundHandler())
req := httptest.NewRequest("GET", "/foo/bar", nil)
h.ServeHTTP(httptest.NewRecorder(), req)
if req.URL.Path != "/foo/bar" {
t.Errorf("StripPrefix should not modify the provided Request, but it did")
}
}
func TestRequestLimit_h1(t *testing.T) { testRequestLimit(t, h1Mode) }
func TestRequestLimit_h2(t *testing.T) { testRequestLimit(t, h2Mode) }
func testRequestLimit(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
t.Fatalf("didn't expect to get request in Handler")
}), optQuietLog)
defer cst.close()
req, _ := NewRequest("GET", cst.ts.URL, nil)
var bytesPerHeader = len("header12345: val12345\r\n")
for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ {
req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i))
}
res, err := cst.c.Do(req)
if res != nil {
defer res.Body.Close()
}
if h2 {
// In HTTP/2, the result depends on a race. If the client has received the
// server's SETTINGS before RoundTrip starts sending the request, then RoundTrip
// will fail with an error. Otherwise, the client should receive a 431 from the
// server.
if err == nil && res.StatusCode != 431 {
t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
}
} else {
// In HTTP/1, we expect a 431 from the server.
// Some HTTP clients may fail on this undefined behavior (server replying and
// closing the connection while the request is still being written), but
// we do support it (at least currently), so we expect a response below.
if err != nil {
t.Fatalf("Do: %v", err)
}
if res.StatusCode != 431 {
t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
}
}
}
type neverEnding byte
func (b neverEnding) Read(p []byte) (n int, err error) {
for i := range p {
p[i] = byte(b)
}
return len(p), nil
}
type countReader struct {
r io.Reader
n *int64
}
func (cr countReader) Read(p []byte) (n int, err error) {
n, err = cr.r.Read(p)
atomic.AddInt64(cr.n, int64(n))
return
}
func TestRequestBodyLimit_h1(t *testing.T) { testRequestBodyLimit(t, h1Mode) }
func TestRequestBodyLimit_h2(t *testing.T) { testRequestBodyLimit(t, h2Mode) }
func testRequestBodyLimit(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
const limit = 1 << 20
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
r.Body = MaxBytesReader(w, r.Body, limit)
n, err := io.Copy(io.Discard, r.Body)
if err == nil {
t.Errorf("expected error from io.Copy")
}
if n != limit {
t.Errorf("io.Copy = %d, want %d", n, limit)
}
}))
defer cst.close()
nWritten := new(int64)
req, _ := NewRequest("POST", cst.ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200))
// Send the POST, but don't care it succeeds or not. The
// remote side is going to reply and then close the TCP
// connection, and HTTP doesn't really define if that's
// allowed or not. Some HTTP clients will get the response
// and some (like ours, currently) will complain that the
// request write failed, without reading the response.
//
// But that's okay, since what we're really testing is that
// the remote side hung up on us before we wrote too much.
_, _ = cst.c.Do(req)
if atomic.LoadInt64(nWritten) > limit*100 {
t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d",
limit, nWritten)
}
}
// TestClientWriteShutdown tests that if the client shuts down the write
// side of their TCP connection, the server doesn't send a 400 Bad Request.
func TestClientWriteShutdown(t *testing.T) {
if runtime.GOOS == "plan9" {
t.Skip("skipping test; see https://golang.org/issue/17906")
}
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
err = conn.(*net.TCPConn).CloseWrite()
if err != nil {
t.Fatalf("CloseWrite: %v", err)
}
donec := make(chan bool)
go func() {
defer close(donec)
bs, err := io.ReadAll(conn)
if err != nil {
t.Errorf("ReadAll: %v", err)
}
got := string(bs)
if got != "" {
t.Errorf("read %q from server; want nothing", got)
}
}()
select {
case <-donec:
case <-time.After(10 * time.Second):
t.Fatalf("timeout")
}
}
// Tests that chunked server responses that write 1 byte at a time are
// buffered before chunk headers are added, not after chunk headers.
func TestServerBufferedChunking(t *testing.T) {
conn := new(testConn)
conn.readBuf.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
conn.closec = make(chan bool, 1)
ls := &oneConnListener{conn}
go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length
rw.Write([]byte{'x'})
rw.Write([]byte{'y'})
rw.Write([]byte{'z'})
}))
<-conn.closec
if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) {
t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q",
conn.writeBuf.Bytes())
}
}
// Tests that the server flushes its response headers out when it's
// ignoring the response body and waits a bit before forcefully
// closing the TCP connection, causing the client to get a RST.
// See https://golang.org/issue/3595
func TestServerGracefulClose(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
Error(w, "bye", StatusUnauthorized)
}))
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
const bodySize = 5 << 20
req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize))
for i := 0; i < bodySize; i++ {
req = append(req, 'x')
}
writeErr := make(chan error)
go func() {
_, err := conn.Write(req)
writeErr <- err
}()
br := bufio.NewReader(conn)
lineNum := 0
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("ReadLine: %v", err)
}
lineNum++
if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") {
t.Errorf("Response line = %q; want a 401", line)
}
}
// Wait for write to finish. This is a broken pipe on both
// Darwin and Linux, but checking this isn't the point of
// the test.
<-writeErr
}
func TestCaseSensitiveMethod_h1(t *testing.T) { testCaseSensitiveMethod(t, h1Mode) }
func TestCaseSensitiveMethod_h2(t *testing.T) { testCaseSensitiveMethod(t, h2Mode) }
func testCaseSensitiveMethod(t *testing.T, h2 bool) {
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
if r.Method != "get" {
t.Errorf(`Got method %q; want "get"`, r.Method)
}
}))
defer cst.close()
req, _ := NewRequest("get", cst.ts.URL, nil)
res, err := cst.c.Do(req)
if err != nil {
t.Error(err)
return
}
res.Body.Close()
}
// TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1
// request (both keep-alive), when a Handler never writes any
// response, the net/http package adds a "Content-Length: 0" response
// header.
func TestContentLengthZero(t *testing.T) {
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {}))
defer ts.Close()
for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} {
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("error dialing: %v", err)
}
_, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version)
if err != nil {
t.Fatalf("error writing: %v", err)
}
req, _ := NewRequest("GET", "/", nil)
res, err := ReadResponse(bufio.NewReader(conn), req)
if err != nil {
t.Fatalf("error reading response: %v", err)
}
if te := res.TransferEncoding; len(te) > 0 {
t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te)
}
if cl := res.ContentLength; cl != 0 {
t.Errorf("For version %q, Content-Length = %v; want 0", version, cl)
}
conn.Close()
}
}
func TestCloseNotifier(t *testing.T) {
defer afterTest(t)
gotReq := make(chan bool, 1)
sawClose := make(chan bool, 1)
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
gotReq <- true
cc := rw.(CloseNotifier).CloseNotify()
<-cc
sawClose <- true
}))
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("error dialing: %v", err)
}
diec := make(chan bool)
go func() {
_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
if err != nil {
t.Error(err)
return
}
<-diec
conn.Close()
}()
For:
for {
select {
case <-gotReq:
diec <- true
case <-sawClose:
break For
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}
ts.Close()
}
// Tests that a pipelined request does not cause the first request's
// Handler's CloseNotify channel to fire.
//
// Issue 13165 (where it used to deadlock), but behavior changed in Issue 23921.
func TestCloseNotifierPipelined(t *testing.T) {
setParallel(t)
defer afterTest(t)
gotReq := make(chan bool, 2)
sawClose := make(chan bool, 2)
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
gotReq <- true
cc := rw.(CloseNotifier).CloseNotify()
select {
case <-cc:
t.Error("unexpected CloseNotify")
case <-time.After(100 * time.Millisecond):
}
sawClose <- true
}))
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("error dialing: %v", err)
}
diec := make(chan bool, 1)
defer close(diec)
go func() {
const req = "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n"
_, err = io.WriteString(conn, req+req) // two requests
if err != nil {
t.Error(err)
return
}
<-diec
conn.Close()
}()
reqs := 0
closes := 0
for {
select {
case <-gotReq:
reqs++
if reqs > 2 {
t.Fatal("too many requests")
}
case <-sawClose:
closes++
if closes > 1 {
return
}
case <-time.After(5 * time.Second):
ts.CloseClientConnections()
t.Fatal("timeout")
}
}
}
func TestCloseNotifierChanLeak(t *testing.T) {
defer afterTest(t)
req := reqBytes("GET / HTTP/1.0\nHost: golang.org")
for i := 0; i < 20; i++ {
var output bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &output,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
// Ignore the return value and never read from
// it, testing that we don't leak goroutines
// on the sending side:
_ = rw.(CloseNotifier).CloseNotify()
})
go Serve(ln, handler)
<-conn.closec
}
}
// Tests that we can use CloseNotifier in one request, and later call Hijack
// on a second request on the same connection.
//
// It also tests that the connReader stitches together its background
// 1-byte read for CloseNotifier when CloseNotifier doesn't fire with
// the rest of the second HTTP later.
//
// Issue 9763.
// HTTP/1-only test. (http2 doesn't have Hijack)
func TestHijackAfterCloseNotifier(t *testing.T) {
defer afterTest(t)
script := make(chan string, 2)
script <- "closenotify"
script <- "hijack"
close(script)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
plan := <-script
switch plan {
default:
panic("bogus plan; too many requests")
case "closenotify":
w.(CloseNotifier).CloseNotify() // discard result
w.Header().Set("X-Addr", r.RemoteAddr)
case "hijack":
c, _, err := w.(Hijacker).Hijack()
if err != nil {
t.Errorf("Hijack in Handler: %v", err)
return
}
if _, ok := c.(*net.TCPConn); !ok {
// Verify it's not wrapped in some type.
// Not strictly a go1 compat issue, but in practice it probably is.
t.Errorf("type of hijacked conn is %T; want *net.TCPConn", c)
}
fmt.Fprintf(c, "HTTP/1.0 200 OK\r\nX-Addr: %v\r\nContent-Length: 0\r\n\r\n", r.RemoteAddr)
c.Close()
return
}
}))
defer ts.Close()
res1, err := Get(ts.URL)
if err != nil {
log.Fatal(err)
}
res2, err := Get(ts.URL)
if err != nil {
log.Fatal(err)
}
addr1 := res1.Header.Get("X-Addr")
addr2 := res2.Header.Get("X-Addr")
if addr1 == "" || addr1 != addr2 {
t.Errorf("addr1, addr2 = %q, %q; want same", addr1, addr2)
}
}
func TestHijackBeforeRequestBodyRead(t *testing.T) {
setParallel(t)
defer afterTest(t)
var requestBody = bytes.Repeat([]byte("a"), 1<<20)
bodyOkay := make(chan bool, 1)
gotCloseNotify := make(chan bool, 1)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
defer close(bodyOkay) // caller will read false if nothing else
reqBody := r.Body
r.Body = nil // to test that server.go doesn't use this value.
gone := w.(CloseNotifier).CloseNotify()
slurp, err := io.ReadAll(reqBody)
if err != nil {
t.Errorf("Body read: %v", err)
return
}
if len(slurp) != len(requestBody) {
t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
return
}
if !bytes.Equal(slurp, requestBody) {
t.Error("Backend read wrong request body.") // 1MB; omitting details
return
}
bodyOkay <- true
select {
case <-gone:
gotCloseNotify <- true
case <-time.After(5 * time.Second):
gotCloseNotify <- false
}
}))
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: foo\r\nContent-Length: %d\r\n\r\n%s",
len(requestBody), requestBody)
if !<-bodyOkay {
// already failed.
return
}
conn.Close()
if !<-gotCloseNotify {
t.Error("timeout waiting for CloseNotify")
}
}
func TestOptions(t *testing.T) {
uric := make(chan string, 2) // only expect 1, but leave space for 2
mux := NewServeMux()
mux.HandleFunc("/", func(w ResponseWriter, r *Request) {
uric <- r.RequestURI
})
ts := httptest.NewServer(mux)
defer ts.Close()
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
// An OPTIONS * request should succeed.
_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
if err != nil {
t.Fatal(err)
}
br := bufio.NewReader(conn)
res, err := ReadResponse(br, &Request{Method: "OPTIONS"})
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 200 {
t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
}
// A GET * request on a ServeMux should fail.
_, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
if err != nil {
t.Fatal(err)
}
res, err = ReadResponse(br, &Request{Method: "GET"})
if err != nil {
t.Fatal(err)
}
if res.StatusCode != 400 {
t.Errorf("Got non-400 response to GET *: %#v", res)
}
res, err = Get(ts.URL + "/second")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if got := <-uric; got != "/second" {
t.Errorf("Handler saw request for %q; want /second", got)
}
}
// Tests regarding the ordering of Write, WriteHeader, Header, and
// Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
// (*response).header to the wire. In Go 1.1, the actual wire flush is
// delayed, so we could maybe tack on a Content-Length and better
// Content-Type after we see more (or all) of the output. To preserve
// compatibility with Go 1, we need to be careful to track which
// headers were live at the time of WriteHeader, so we write the same
// ones, even if the handler modifies them (~erroneously) after the
// first Write.
func TestHeaderToWire(t *testing.T) {
tests := []struct {
name string
handler func(ResponseWriter, *Request)
check func(got, logs string) error
}{
{
name: "write without Header",
handler: func(rw ResponseWriter, r *Request) {
rw.Write([]byte("hello world"))
},
check: func(got, logs string) error {
if !strings.Contains(got, "Content-Length:") {
return errors.New("no content-length")
}
if !strings.Contains(got, "Content-Type: text/plain") {
return errors.New("no content-type")
}
return nil
},
},
{
name: "Header mutation before write",
handler: func(rw ResponseWriter, r *Request) {
h := rw.Header()
h.Set("Content-Type", "some/type")
rw.Write([]byte("hello world"))
h.Set("Too-Late", "bogus")
},
check: func(got, logs string) error {
if !strings.Contains(got, "Content-Length:") {
return errors.New("no content-length")
}
if !strings.Contains(got, "Content-Type: some/type") {
return errors.New("wrong content-type")
}
if strings.Contains(got, "Too-Late") {
return errors.New("don't want too-late header")
}
return nil
},
},
{
name: "write then useless Header mutation",
handler: func(rw ResponseWriter, r *Request) {
rw.Write([]byte("hello world"))
rw.Header().Set("Too-Late", "Write already wrote headers")
},
check: func(got, logs string) error {
if strings.Contains(got, "Too-Late") {
return errors.New("header appeared from after WriteHeader")
}
return nil
},
},
{
name: "flush then write",
handler: func(rw ResponseWriter, r *Request) {
rw.(Flusher).Flush()
rw.Write([]byte("post-flush"))
rw.Header().Set("Too-Late", "Write already wrote headers")
},
check: func(got, logs string) error {
if !strings.Contains(got, "Transfer-Encoding: chunked") {
return errors.New("not chunked")
}
if strings.Contains(got, "Too-Late") {
return errors.New("header appeared from after WriteHeader")
}
return nil
},
},
{
name: "header then flush",
handler: func(rw ResponseWriter, r *Request) {
rw.Header().Set("Content-Type", "some/type")
rw.(Flusher).Flush()
rw.Write([]byte("post-flush"))
rw.Header().Set("Too-Late", "Write already wrote headers")
},
check: func(got, logs string) error {
if !strings.Contains(got, "Transfer-Encoding: chunked") {
return errors.New("not chunked")
}
if strings.Contains(got, "Too-Late") {
return errors.New("header appeared from after WriteHeader")
}
if !strings.Contains(got, "Content-Type: some/type") {
return errors.New("wrong content-type")
}
return nil
},
},
{
name: "sniff-on-first-write content-type",
handler: func(rw ResponseWriter, r *Request) {
rw.Write([]byte("<html><head></head><body>some html</body></html>"))
rw.Header().Set("Content-Type", "x/wrong")
},
check: func(got, logs string) error {
if !strings.Contains(got, "Content-Type: text/html") {
return errors.New("wrong content-type; want html")
}
return nil
},
},
{
name: "explicit content-type wins",
handler: func(rw ResponseWriter, r *Request) {
rw.Header().Set("Content-Type", "some/type")
rw.Write([]byte("<html><head></head><body>some html</body></html>"))
},
check: func(got, logs string) error {
if !strings.Contains(got, "Content-Type: some/type") {
return errors.New("wrong content-type; want html")
}
return nil
},
},
{
name: "empty handler",
handler: func(rw ResponseWriter, r *Request) {
},
check: func(got, logs string) error {
if !strings.Contains(got, "Content-Length: 0") {
return errors.New("want 0 content-length")
}
return nil
},
},
{
name: "only Header, no write",
handler: func(rw ResponseWriter, r *Request) {
rw.Header().Set("Some-Header", "some-value")
},
check: func(got, logs string) error {
if !strings.Contains(got, "Some-Header") {
return errors.New("didn't get header")
}
return nil
},
},
{
name: "WriteHeader call",
handler: func(rw ResponseWriter, r *Request) {
rw.WriteHeader(404)
rw.Header().Set("Too-Late", "some-value")
},
check: func(got, logs string) error {
if !strings.Contains(got, "404") {
return errors.New("wrong status")
}
if strings.Contains(got, "Too-Late") {
return errors.New("shouldn't have seen Too-Late")
}
return nil
},
},
}
for _, tc := range tests {
ht := newHandlerTest(HandlerFunc(tc.handler))
got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
logs := ht.logbuf.String()
if err := tc.check(got, logs); err != nil {
t.Errorf("%s: %v\nGot response:\n%s\n\n%s", tc.name, err, got, logs)
}
}
}
type errorListener struct {
errs []error
}
func (l *errorListener) Accept() (c net.Conn, err error) {
if len(l.errs) == 0 {
return nil, io.EOF
}
err = l.errs[0]
l.errs = l.errs[1:]
return
}
func (l *errorListener) Close() error {
return nil
}
func (l *errorListener) Addr() net.Addr {
return dummyAddr("test-address")
}
func TestAcceptMaxFds(t *testing.T) {
setParallel(t)
ln := &errorListener{[]error{
&net.OpError{
Op: "accept",
Err: syscall.EMFILE,
}}}
server := &Server{
Handler: HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})),
ErrorLog: log.New(io.Discard, "", 0), // noisy otherwise
}
err := server.Serve(ln)
if err != io.EOF {
t.Errorf("got error %v, want EOF", err)
}
}
func TestWriteAfterHijack(t *testing.T) {
req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
var buf bytes.Buffer
wrotec := make(chan bool, 1)
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &buf,
closec: make(chan bool, 1),
}
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
conn, bufrw, err := rw.(Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
go func() {
bufrw.Write([]byte("[hijack-to-bufw]"))
bufrw.Flush()
conn.Write([]byte("[hijack-to-conn]"))
conn.Close()
wrotec <- true
}()
})
ln := &oneConnListener{conn: conn}
go Serve(ln, handler)
<-conn.closec
<-wrotec
if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w {
t.Errorf("wrote %q; want %q", g, w)
}
}
func TestDoubleHijack(t *testing.T) {
req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
var buf bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &buf,
closec: make(chan bool, 1),
}
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
conn, _, err := rw.(Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_, _, err = rw.(Hijacker).Hijack()
if err == nil {
t.Errorf("got err = nil; want err != nil")
}
conn.Close()
})
ln := &oneConnListener{conn: conn}
go Serve(ln, handler)
<-conn.closec
}
// https://golang.org/issue/5955
// Note that this does not test the "request too large"
// exit path from the http server. This is intentional;
// not sending Connection: close is just a minor wire
// optimization and is pointless if dealing with a
// badly behaved client.
func TestHTTP10ConnectionHeader(t *testing.T) {
defer afterTest(t)
mux := NewServeMux()
mux.Handle("/", HandlerFunc(func(ResponseWriter, *Request) {}))
ts := httptest.NewServer(mux)
defer ts.Close()
// net/http uses HTTP/1.1 for requests, so write requests manually
tests := []struct {
req string // raw http request
expect []string // expected Connection header(s)
}{
{
req: "GET / HTTP/1.0\r\n\r\n",
expect: nil,
},
{
req: "OPTIONS * HTTP/1.0\r\n\r\n",
expect: nil,
},
{
req: "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n",
expect: []string{"keep-alive"},
},
}
for _, tt := range tests {
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal("dial err:", err)
}
_, err = fmt.Fprint(conn, tt.req)
if err != nil {
t.Fatal("conn write err:", err)
}
resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"})
if err != nil {
t.Fatal("ReadResponse err:", err)
}
conn.Close()
resp.Body.Close()
got := resp.Header["Connection"]
if !reflect.DeepEqual(got, tt.expect) {
t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect)
}
}
}
// See golang.org/issue/5660
func TestServerReaderFromOrder_h1(t *testing.T) { testServerReaderFromOrder(t, h1Mode) }
func TestServerReaderFromOrder_h2(t *testing.T) { testServerReaderFromOrder(t, h2Mode) }
func testServerReaderFromOrder(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
pr, pw := io.Pipe()
const size = 3 << 20
cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path
done := make(chan bool)
go func() {
io.Copy(rw, pr)
close(done)
}()
time.Sleep(25 * time.Millisecond) // give Copy a chance to break things
n, err := io.Copy(io.Discard, req.Body)
if err != nil {
t.Errorf("handler Copy: %v", err)
return
}
if n != size {
t.Errorf("handler Copy = %d; want %d", n, size)
}
pw.Write([]byte("hi"))
pw.Close()
<-done
}))
defer cst.close()
req, err := NewRequest("POST", cst.ts.URL, io.LimitReader(neverEnding('a'), size))
if err != nil {
t.Fatal(err)
}
res, err := cst.c.Do(req)
if err != nil {
t.Fatal(err)
}
all, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if string(all) != "hi" {
t.Errorf("Body = %q; want hi", all)
}
}
// Issue 6157, Issue 6685
func TestCodesPreventingContentTypeAndBody(t *testing.T) {
for _, code := range []int{StatusNotModified, StatusNoContent, StatusContinue} {
ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
if r.URL.Path == "/header" {
w.Header().Set("Content-Length", "123")
}
w.WriteHeader(code)
if r.URL.Path == "/more" {
w.Write([]byte("stuff"))
}
}))
for _, req := range []string{
"GET / HTTP/1.0",
"GET /header HTTP/1.0",
"GET /more HTTP/1.0",
"GET / HTTP/1.1\nHost: foo",
"GET /header HTTP/1.1\nHost: foo",
"GET /more HTTP/1.1\nHost: foo",
} {
got := ht.rawResponse(req)
wantStatus := fmt.Sprintf("%d %s", code, StatusText(code))
if !strings.Contains(got, wantStatus) {
t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got)
} else if strings.Contains(got, "Content-Length") {
t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got)
} else if strings.Contains(got, "stuff") {
t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got)
}
}
}
}
func TestContentTypeOkayOn204(t *testing.T) {
ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", "123") // suppressed
w.Header().Set("Content-Type", "foo/bar")
w.WriteHeader(204)
}))
got := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
if !strings.Contains(got, "Content-Type: foo/bar") {
t.Errorf("Response = %q; want Content-Type: foo/bar", got)
}
if strings.Contains(got, "Content-Length: 123") {
t.Errorf("Response = %q; don't want a Content-Length", got)
}
}
// Issue 6995
// A server Handler can receive a Request, and then turn around and
// give a copy of that Request.Body out to the Transport (e.g. any
// proxy). So then two people own that Request.Body (both the server
// and the http client), and both think they can close it on failure.
// Therefore, all incoming server requests Bodies need to be thread-safe.
func TestTransportAndServerSharedBodyRace_h1(t *testing.T) {
testTransportAndServerSharedBodyRace(t, h1Mode)
}
func TestTransportAndServerSharedBodyRace_h2(t *testing.T) {
testTransportAndServerSharedBodyRace(t, h2Mode)
}
func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
const bodySize = 1 << 20
// errorf is like t.Errorf, but also writes to println. When
// this test fails, it hangs. This helps debugging and I've
// added this enough times "temporarily". It now gets added
// full time.
errorf := func(format string, args ...interface{}) {
v := fmt.Sprintf(format, args...)
println(v)
t.Error(v)
}
unblockBackend := make(chan bool)
backend := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
gone := rw.(CloseNotifier).CloseNotify()
didCopy := make(chan interface{})
go func() {
n, err := io.CopyN(rw, req.Body, bodySize)
didCopy <- []interface{}{n, err}
}()
isGone := false
Loop:
for {
select {
case <-didCopy:
break Loop
case <-gone:
isGone = true
case <-time.After(time.Second):
println("1 second passes in backend, proxygone=", isGone)
}
}
<-unblockBackend
}))
var quitTimer *time.Timer
defer func() { quitTimer.Stop() }()
defer backend.close()
backendRespc := make(chan *Response, 1)
var proxy *clientServerTest
proxy = newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
req2, _ := NewRequest("POST", backend.ts.URL, req.Body)
req2.ContentLength = bodySize
cancel := make(chan struct{})
req2.Cancel = cancel
bresp, err := proxy.c.Do(req2)
if err != nil {
errorf("Proxy outbound request: %v", err)
return
}
_, err = io.CopyN(io.Discard, bresp.Body, bodySize/2)
if err != nil {
errorf("Proxy copy error: %v", err)
return
}
backendRespc <- bresp // to close later
// Try to cause a race: Both the Transport and the proxy handler's Server
// will try to read/close req.Body (aka req2.Body)
if h2 {
close(cancel)
} else {
proxy.c.Transport.(*Transport).CancelRequest(req2)
}
rw.Write([]byte("OK"))
}))
defer proxy.close()
defer func() {
// Before we shut down our two httptest.Servers, start a timer.
// We choose 7 seconds because httptest.Server starts logging
// warnings to stderr at 5 seconds. If we don't disarm this bomb
// in 7 seconds (after the two httptest.Server.Close calls above),
// then we explode with stacks.
quitTimer = time.AfterFunc(7*time.Second, func() {
debug.SetTraceback("ALL")
stacks := make([]byte, 1<<20)
stacks = stacks[:runtime.Stack(stacks, true)]
fmt.Fprintf(os.Stderr, "%s", stacks)
log.Fatalf("Timeout.")
})
}()
defer close(unblockBackend)
req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize))
res, err := proxy.c.Do(req)
if err != nil {
t.Fatalf("Original request: %v", err)
}
// Cleanup, so we don't leak goroutines.
res.Body.Close()
select {
case res := <-backendRespc:
res.Body.Close()
default:
// We failed earlier. (e.g. on proxy.c.Do(req2))
}
}
// Test that a hanging Request.Body.Read from another goroutine can't
// cause the Handler goroutine's Request.Body.Close to block.
// See issue 7121.
func TestRequestBodyCloseDoesntBlock(t *testing.T) {
if testing.Short() {
t.Skip("skipping in -short mode")
}
defer afterTest(t)
readErrCh := make(chan error, 1)
errCh := make(chan error, 2)
server := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
go func(body io.Reader) {
_, err := body.Read(make([]byte, 100))
readErrCh <- err
}(req.Body)
time.Sleep(500 * time.Millisecond)
}))
defer server.Close()
closeConn := make(chan bool)
defer close(closeConn)
go func() {
conn, err := net.Dial("tcp", server.Listener.Addr().String())
if err != nil {
errCh <- err
return
}
defer conn.Close()
_, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n"))
if err != nil {
errCh <- err
return
}
// And now just block, making the server block on our
// 100000 bytes of body that will never arrive.
<-closeConn
}()
select {
case err := <-readErrCh:
if err == nil {
t.Error("Read was nil. Expected error.")
}
case err := <-errCh:
t.Error(err)
case <-time.After(5 * time.Second):
t.Error("timeout")
}
}
// test that ResponseWriter implements io.StringWriter.
func TestResponseWriterWriteString(t *testing.T) {
okc := make(chan bool, 1)
ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
_, ok := w.(io.StringWriter)
okc <- ok
}))
ht.rawResponse("GET / HTTP/1.0")
select {
case ok := <-okc:
if !ok {
t.Error("ResponseWriter did not implement io.StringWriter")
}
default:
t.Error("handler was never called")
}
}
func TestAppendTime(t *testing.T) {
var b [len(TimeFormat)]byte
t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60))
res := ExportAppendTime(b[:0], t1)
t2, err := ParseTime(string(res))
if err != nil {
t.Fatalf("Error parsing time: %s", err)
}
if !t1.Equal(t2) {
t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res))
}
}
func TestServerConnState(t *testing.T) {
setParallel(t)
defer afterTest(t)
handler := map[string]func(w ResponseWriter, r *Request){
"/": func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "Hello.")
},
"/close": func(w ResponseWriter, r *Request) {
w.Header().Set("Connection", "close")
fmt.Fprintf(w, "Hello.")
},
"/hijack": func(w ResponseWriter, r *Request) {
c, _, _ := w.(Hijacker).Hijack()
c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
c.Close()
},
"/hijack-panic": func(w ResponseWriter, r *Request) {
c, _, _ := w.(Hijacker).Hijack()
c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
c.Close()
panic("intentional panic")
},
}
// A stateLog is a log of states over the lifetime of a connection.
type stateLog struct {
active net.Conn // The connection for which the log is recorded; set to the first connection seen in StateNew.
got []ConnState
want []ConnState
complete chan<- struct{} // If non-nil, closed when either 'got' is equal to 'want', or 'got' is no longer a prefix of 'want'.
}
activeLog := make(chan *stateLog, 1)
// wantLog invokes doRequests, then waits for the resulting connection to
// either pass through the sequence of states in want or enter a state outside
// of that sequence.
wantLog := func(doRequests func(), want ...ConnState) {
t.Helper()
complete := make(chan struct{})
activeLog <- &stateLog{want: want, complete: complete}
doRequests()
stateDelay := 5 * time.Second
if deadline, ok := t.Deadline(); ok {
// Allow an arbitrarily long delay.
// This test was observed to be flaky on the darwin-arm64-corellium builder,
// so we're increasing the deadline to see if it starts passing.
// See https://golang.org/issue/37322.
const arbitraryCleanupMargin = 1 * time.Second
stateDelay = time.Until(deadline) - arbitraryCleanupMargin
}
timer := time.NewTimer(stateDelay)
select {
case <-timer.C:
t.Errorf("Timed out after %v waiting for connection to change state.", stateDelay)
case <-complete:
timer.Stop()
}
sl := <-activeLog
if !reflect.DeepEqual(sl.got, sl.want) {
t.Errorf("Request(s) produced unexpected state sequence.\nGot: %v\nWant: %v", sl.got, sl.want)
}
// Don't return sl to activeLog: we don't expect any further states after
// this point, and want to keep the ConnState callback blocked until the
// next call to wantLog.
}
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
handler[r.URL.Path](w, r)
}))
defer func() {
activeLog <- &stateLog{} // If the test failed, allow any remaining ConnState callbacks to complete.
ts.Close()
}()
ts.Config.ErrorLog = log.New(io.Discard, "", 0)
ts.Config.ConnState = func(c net.Conn, state ConnState) {
if c == nil {
t.Errorf("nil conn seen in state %s", state)
return
}
sl := <-activeLog
if sl.active == nil && state == StateNew {
sl.active = c
} else if sl.active != c {
t.Errorf("unexpected conn in state %s", state)
activeLog <- sl
return
}
sl.got = append(sl.got, state)
if sl.complete != nil && (len(sl.got) >= len(sl.want) || !reflect.DeepEqual(sl.got, sl.want[:len(sl.got)])) {
close(sl.complete)
sl.complete = nil
}
activeLog <- sl
}
ts.Start()
c := ts.Client()
mustGet := func(url string, headers ...string) {
t.Helper()
req, err := NewRequest("GET", url, nil)
if err != nil {
t.Fatal(err)
}
for len(headers) > 0 {
req.Header.Add(headers[0], headers[1])
headers = headers[2:]
}
res, err := c.Do(req)
if err != nil {
t.Errorf("Error fetching %s: %v", url, err)
return
}
_, err = io.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
t.Errorf("Error reading %s: %v", url, err)
}
}
wantLog(func() {
mustGet(ts.URL + "/")
mustGet(ts.URL + "/close")
}, StateNew, StateActive, StateIdle, StateActive, StateClosed)
wantLog(func() {
mustGet(ts.URL + "/")
mustGet(ts.URL+"/", "Connection", "close")
}, StateNew, StateActive, StateIdle, StateActive, StateClosed)
wantLog(func() {
mustGet(ts.URL + "/hijack")
}, StateNew, StateActive, StateHijacked)
wantLog(func() {
mustGet(ts.URL + "/hijack-panic")
}, StateNew, StateActive, StateHijacked)
wantLog(func() {
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
c.Close()
}, StateNew, StateClosed)
wantLog(func() {
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil {
t.Fatal(err)
}
c.Read(make([]byte, 1)) // block until server hangs up on us
c.Close()
}, StateNew, StateActive, StateClosed)
wantLog(func() {
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
t.Fatal(err)
}
res, err := ReadResponse(bufio.NewReader(c), nil)
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(io.Discard, res.Body); err != nil {
t.Fatal(err)
}
c.Close()
}, StateNew, StateActive, StateIdle, StateClosed)
}
func TestServerKeepAlivesEnabled(t *testing.T) {
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
ts.Config.SetKeepAlivesEnabled(false)
ts.Start()
defer ts.Close()
res, err := Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if !res.Close {
t.Errorf("Body.Close == false; want true")
}
}
// golang.org/issue/7856
func TestServerEmptyBodyRace_h1(t *testing.T) { testServerEmptyBodyRace(t, h1Mode) }
func TestServerEmptyBodyRace_h2(t *testing.T) { testServerEmptyBodyRace(t, h2Mode) }
func testServerEmptyBodyRace(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
var n int32
cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
atomic.AddInt32(&n, 1)
}), optQuietLog)
defer cst.close()
var wg sync.WaitGroup
const reqs = 20
for i := 0; i < reqs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
// Try to deflake spurious "connection reset by peer" under load.
// See golang.org/issue/22540.
time.Sleep(10 * time.Millisecond)
res, err = cst.c.Get(cst.ts.URL)
if err != nil {
t.Error(err)
return
}
}
defer res.Body.Close()
_, err = io.Copy(io.Discard, res.Body)
if err != nil {
t.Error(err)
return
}
}()
}
wg.Wait()
if got := atomic.LoadInt32(&n); got != reqs {
t.Errorf("handler ran %d times; want %d", got, reqs)
}
}
func TestServerConnStateNew(t *testing.T) {
sawNew := false // if the test is buggy, we'll race on this variable.
srv := &Server{
ConnState: func(c net.Conn, state ConnState) {
if state == StateNew {
sawNew = true // testing that this write isn't racy
}
},
Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant
}
srv.Serve(&oneConnListener{
conn: &rwTestConn{
Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"),
Writer: io.Discard,
},
})
if !sawNew { // testing that this read isn't racy
t.Error("StateNew not seen")
}
}
type closeWriteTestConn struct {
rwTestConn
didCloseWrite bool
}
func (c *closeWriteTestConn) CloseWrite() error {
c.didCloseWrite = true
return nil
}
func TestCloseWrite(t *testing.T) {
setParallel(t)
var srv Server
var testConn closeWriteTestConn
c := ExportServerNewConn(&srv, &testConn)
ExportCloseWriteAndWait(c)
if !testConn.didCloseWrite {
t.Error("didn't see CloseWrite call")
}
}
// This verifies that a handler can Flush and then Hijack.
//
// A similar test crashed once during development, but it was only
// testing this tangentially and temporarily until another TODO was
// fixed.
//
// So add an explicit test for this.
func TestServerFlushAndHijack(t *testing.T) {
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
io.WriteString(w, "Hello, ")
w.(Flusher).Flush()
conn, buf, _ := w.(Hijacker).Hijack()
buf.WriteString("6\r\nworld!\r\n0\r\n\r\n")
if err := buf.Flush(); err != nil {
t.Error(err)
}
if err := conn.Close(); err != nil {
t.Error(err)
}
}))
defer ts.Close()
res, err := Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
all, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if want := "Hello, world!"; string(all) != want {
t.Errorf("Got %q; want %q", all, want)
}
}
// golang.org/issue/8534 -- the Server shouldn't reuse a connection
// for keep-alive after it's seen any Write error (e.g. a timeout) on
// that net.Conn.
//
// To test, verify we don't timeout or see fewer unique client
// addresses (== unique connections) than requests.
func TestServerKeepAliveAfterWriteError(t *testing.T) {
if testing.Short() {
t.Skip("skipping in -short mode")
}
defer afterTest(t)
const numReq = 3
addrc := make(chan string, numReq)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
addrc <- r.RemoteAddr
time.Sleep(500 * time.Millisecond)
w.(Flusher).Flush()
}))
ts.Config.WriteTimeout = 250 * time.Millisecond
ts.Start()
defer ts.Close()
errc := make(chan error, numReq)
go func() {
defer close(errc)
for i := 0; i < numReq; i++ {
res, err := Get(ts.URL)
if res != nil {
res.Body.Close()
}
errc <- err
}
}()
timeout := time.NewTimer(numReq * 2 * time.Second) // 4x overkill
defer timeout.Stop()
addrSeen := map[string]bool{}
numOkay := 0
for {
select {
case v := <-addrc:
addrSeen[v] = true
case err, ok := <-errc:
if !ok {
if len(addrSeen) != numReq {
t.Errorf("saw %d unique client addresses; want %d", len(addrSeen), numReq)
}
if numOkay != 0 {
t.Errorf("got %d successful client requests; want 0", numOkay)
}
return
}
if err == nil {
numOkay++
}
case <-timeout.C:
t.Fatal("timeout waiting for requests to complete")
}
}
}
// Issue 9987: shouldn't add automatic Content-Length (or
// Content-Type) if a Transfer-Encoding was set by the handler.
func TestNoContentLengthIfTransferEncoding(t *testing.T) {
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Transfer-Encoding", "foo")
io.WriteString(w, "<html>")
}))
defer ts.Close()
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
t.Fatal(err)
}
bs := bufio.NewScanner(c)
var got bytes.Buffer
for bs.Scan() {
if strings.TrimSpace(bs.Text()) == "" {
break
}
got.WriteString(bs.Text())
got.WriteByte('\n')
}
if err := bs.Err(); err != nil {
t.Fatal(err)
}
if strings.Contains(got.String(), "Content-Length") {
t.Errorf("Unexpected Content-Length in response headers: %s", got.String())
}
if strings.Contains(got.String(), "Content-Type") {
t.Errorf("Unexpected Content-Type in response headers: %s", got.String())
}
}
// tolerate extra CRLF(s) before Request-Line on subsequent requests on a conn
// Issue 10876.
func TestTolerateCRLFBeforeRequestLine(t *testing.T) {
req := []byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
"\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it
"GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n")
var buf bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &buf,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
numReq := 0
go Serve(ln, HandlerFunc(func(rw ResponseWriter, r *Request) {
numReq++
}))
<-conn.closec
if numReq != 2 {
t.Errorf("num requests = %d; want 2", numReq)
t.Logf("Res: %s", buf.Bytes())
}
}
func TestIssue13893_Expect100(t *testing.T) {
// test that the Server doesn't filter out Expect headers.
req := reqBytes(`PUT /readbody HTTP/1.1
User-Agent: PycURL/7.22.0
Host: 127.0.0.1:9000
Accept: */*
Expect: 100-continue
Content-Length: 10
HelloWorld
`)
var buf bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &buf,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
if _, ok := r.Header["Expect"]; !ok {
t.Error("Expect header should not be filtered out")
}
}))
<-conn.closec
}
func TestIssue11549_Expect100(t *testing.T) {
req := reqBytes(`PUT /readbody HTTP/1.1
User-Agent: PycURL/7.22.0
Host: 127.0.0.1:9000
Accept: */*
Expect: 100-continue
Content-Length: 10
HelloWorldPUT /noreadbody HTTP/1.1
User-Agent: PycURL/7.22.0
Host: 127.0.0.1:9000
Accept: */*
Expect: 100-continue
Content-Length: 10
GET /should-be-ignored HTTP/1.1
Host: foo
`)
var buf bytes.Buffer
conn := &rwTestConn{
Reader: bytes.NewReader(req),
Writer: &buf,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
numReq := 0
go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
numReq++
if r.URL.Path == "/readbody" {
io.ReadAll(r.Body)
}
io.WriteString(w, "Hello world!")
}))
<-conn.closec
if numReq != 2 {
t.Errorf("num requests = %d; want 2", numReq)
}
if !strings.Contains(buf.String(), "Connection: close\r\n") {
t.Errorf("expected 'Connection: close' in response; got: %s", buf.String())
}
}
// If a Handler finishes and there's an unread request body,
// verify the server try to do implicit read on it before replying.
func TestHandlerFinishSkipBigContentLengthRead(t *testing.T) {
setParallel(t)
conn := &testConn{closec: make(chan bool)}
conn.readBuf.Write([]byte(fmt.Sprintf(
"POST / HTTP/1.1\r\n" +
"Host: test\r\n" +
"Content-Length: 9999999999\r\n" +
"\r\n" + strings.Repeat("a", 1<<20))))
ls := &oneConnListener{conn}
var inHandlerLen int
go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
inHandlerLen = conn.readBuf.Len()
rw.WriteHeader(404)
}))
<-conn.closec
afterHandlerLen := conn.readBuf.Len()
if afterHandlerLen != inHandlerLen {
t.Errorf("unexpected implicit read. Read buffer went from %d -> %d", inHandlerLen, afterHandlerLen)
}
}
func TestHandlerSetsBodyNil_h1(t *testing.T) { testHandlerSetsBodyNil(t, h1Mode) }
func TestHandlerSetsBodyNil_h2(t *testing.T) { testHandlerSetsBodyNil(t, h2Mode) }
func testHandlerSetsBodyNil(t *testing.T, h2 bool) {
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
r.Body = nil
fmt.Fprintf(w, "%v", r.RemoteAddr)
}))
defer cst.close()
get := func() string {
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return string(slurp)
}
a, b := get(), get()
if a != b {
t.Errorf("Failed to reuse connections between requests: %v vs %v", a, b)
}
}
// Test that we validate the Host header.
// Issue 11206 (invalid bytes in Host) and 13624 (Host present in HTTP/1.1)
func TestServerValidatesHostHeader(t *testing.T) {
tests := []struct {
proto string
host string
want int
}{
{"HTTP/0.9", "", 505},
{"HTTP/1.1", "", 400},
{"HTTP/1.1", "Host: \r\n", 200},
{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
{"HTTP/1.1", "Host: foo.com\r\n", 200},
{"HTTP/1.1", "Host: foo-bar_baz.com\r\n", 200},
{"HTTP/1.1", "Host: foo.com:80\r\n", 200},
{"HTTP/1.1", "Host: ::1\r\n", 200},
{"HTTP/1.1", "Host: [::1]\r\n", 200}, // questionable without port, but accept it
{"HTTP/1.1", "Host: [::1]:80\r\n", 200},
{"HTTP/1.1", "Host: [::1%25en0]:80\r\n", 200},
{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
{"HTTP/1.1", "Host: \x06\r\n", 400},
{"HTTP/1.1", "Host: \xff\r\n", 400},
{"HTTP/1.1", "Host: {\r\n", 400},
{"HTTP/1.1", "Host: }\r\n", 400},
{"HTTP/1.1", "Host: first\r\nHost: second\r\n", 400},
// HTTP/1.0 can lack a host header, but if present
// must play by the rules too:
{"HTTP/1.0", "", 200},
{"HTTP/1.0", "Host: first\r\nHost: second\r\n", 400},
{"HTTP/1.0", "Host: \xff\r\n", 400},
// Make an exception for HTTP upgrade requests:
{"PRI * HTTP/2.0", "", 200},
// Also an exception for CONNECT requests: (Issue 18215)
{"CONNECT golang.org:443 HTTP/1.1", "", 200},
// But not other HTTP/2 stuff:
{"PRI / HTTP/2.0", "", 505},
{"GET / HTTP/2.0", "", 505},
{"GET / HTTP/3.0", "", 505},
}
for _, tt := range tests {
conn := &testConn{closec: make(chan bool, 1)}
methodTarget := "GET / "
if !strings.HasPrefix(tt.proto, "HTTP/") {
methodTarget = ""
}
io.WriteString(&conn.readBuf, methodTarget+tt.proto+"\r\n"+tt.host+"\r\n")
ln := &oneConnListener{conn}
srv := Server{
ErrorLog: quietLog,
Handler: HandlerFunc(func(ResponseWriter, *Request) {}),
}
go srv.Serve(ln)
<-conn.closec
res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
if err != nil {
t.Errorf("For %s %q, ReadResponse: %v", tt.proto, tt.host, res)
continue
}
if res.StatusCode != tt.want {
t.Errorf("For %s %q, Status = %d; want %d", tt.proto, tt.host, res.StatusCode, tt.want)
}
}
}
func TestServerHandlersCanHandleH2PRI(t *testing.T) {
const upgradeResponse = "upgrade here"
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
conn, br, err := w.(Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
defer conn.Close()
if r.Method != "PRI" || r.RequestURI != "*" {
t.Errorf("Got method/target %q %q; want PRI *", r.Method, r.RequestURI)
return
}
if !r.Close {
t.Errorf("Request.Close = true; want false")
}
const want = "SM\r\n\r\n"
buf := make([]byte, len(want))
n, err := io.ReadFull(br, buf)
if err != nil || string(buf[:n]) != want {
t.Errorf("Read = %v, %v (%q), want %q", n, err, buf[:n], want)
return
}
io.WriteString(conn, upgradeResponse)
}))
defer ts.Close()
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
slurp, err := io.ReadAll(c)
if err != nil {
t.Fatal(err)
}
if string(slurp) != upgradeResponse {
t.Errorf("Handler response = %q; want %q", slurp, upgradeResponse)
}
}
// Test that we validate the valid bytes in HTTP/1 headers.
// Issue 11207.
func TestServerValidatesHeaders(t *testing.T) {
setParallel(t)
tests := []struct {
header string
want int
}{
{"", 200},
{"Foo: bar\r\n", 200},
{"X-Foo: bar\r\n", 200},
{"Foo: a space\r\n", 200},
{"A space: foo\r\n", 400}, // space in header
{"foo\xffbar: foo\r\n", 400}, // binary in header
{"foo\x00bar: foo\r\n", 400}, // binary in header
{"Foo: " + strings.Repeat("x", 1<<21) + "\r\n", 431}, // header too large
// Spaces between the header key and colon are not allowed.
// See RFC 7230, Section 3.2.4.
{"Foo : bar\r\n", 400},
{"Foo\t: bar\r\n", 400},
{"foo: foo foo\r\n", 200}, // LWS space is okay
{"foo: foo\tfoo\r\n", 200}, // LWS tab is okay
{"foo: foo\x00foo\r\n", 400}, // CTL 0x00 in value is bad
{"foo: foo\x7ffoo\r\n", 400}, // CTL 0x7f in value is bad
{"foo: foo\xfffoo\r\n", 200}, // non-ASCII high octets in value are fine
}
for _, tt := range tests {
conn := &testConn{closec: make(chan bool, 1)}
io.WriteString(&conn.readBuf, "GET / HTTP/1.1\r\nHost: foo\r\n"+tt.header+"\r\n")
ln := &oneConnListener{conn}
srv := Server{
ErrorLog: quietLog,
Handler: HandlerFunc(func(ResponseWriter, *Request) {}),
}
go srv.Serve(ln)
<-conn.closec
res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
if err != nil {
t.Errorf("For %q, ReadResponse: %v", tt.header, res)
continue
}
if res.StatusCode != tt.want {
t.Errorf("For %q, Status = %d; want %d", tt.header, res.StatusCode, tt.want)
}
}
}
func TestServerRequestContextCancel_ServeHTTPDone_h1(t *testing.T) {
testServerRequestContextCancel_ServeHTTPDone(t, h1Mode)
}
func TestServerRequestContextCancel_ServeHTTPDone_h2(t *testing.T) {
testServerRequestContextCancel_ServeHTTPDone(t, h2Mode)
}
func testServerRequestContextCancel_ServeHTTPDone(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
ctxc := make(chan context.Context, 1)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
ctx := r.Context()
select {
case <-ctx.Done():
t.Error("should not be Done in ServeHTTP")
default:
}
ctxc <- ctx
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
ctx := <-ctxc
select {
case <-ctx.Done():
default:
t.Error("context should be done after ServeHTTP completes")
}
}
// Tests that the Request.Context available to the Handler is canceled
// if the peer closes their TCP connection. This requires that the server
// is always blocked in a Read call so it notices the EOF from the client.
// See issues 15927 and 15224.
func TestServerRequestContextCancel_ConnClose(t *testing.T) {
setParallel(t)
defer afterTest(t)
inHandler := make(chan struct{})
handlerDone := make(chan struct{})
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
close(inHandler)
select {
case <-r.Context().Done():
case <-time.After(3 * time.Second):
t.Errorf("timeout waiting for context to be done")
}
close(handlerDone)
}))
defer ts.Close()
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer c.Close()
io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
select {
case <-inHandler:
case <-time.After(3 * time.Second):
t.Fatalf("timeout waiting to see ServeHTTP get called")
}
c.Close() // this should trigger the context being done
select {
case <-handlerDone:
case <-time.After(4 * time.Second):
t.Fatalf("timeout waiting to see ServeHTTP exit")
}
}
func TestServerContext_ServerContextKey_h1(t *testing.T) {
testServerContext_ServerContextKey(t, h1Mode)
}
func TestServerContext_ServerContextKey_h2(t *testing.T) {
testServerContext_ServerContextKey(t, h2Mode)
}
func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
ctx := r.Context()
got := ctx.Value(ServerContextKey)
if _, ok := got.(*Server); !ok {
t.Errorf("context value = %T; want *http.Server", got)
}
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
}
func TestServerContext_LocalAddrContextKey_h1(t *testing.T) {
testServerContext_LocalAddrContextKey(t, h1Mode)
}
func TestServerContext_LocalAddrContextKey_h2(t *testing.T) {
testServerContext_LocalAddrContextKey(t, h2Mode)
}
func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
ch := make(chan interface{}, 1)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
ch <- r.Context().Value(LocalAddrContextKey)
}))
defer cst.close()
if _, err := cst.c.Head(cst.ts.URL); err != nil {
t.Fatal(err)
}
host := cst.ts.Listener.Addr().String()
select {
case got := <-ch:
if addr, ok := got.(net.Addr); !ok {
t.Errorf("local addr value = %T; want net.Addr", got)
} else if fmt.Sprint(addr) != host {
t.Errorf("local addr = %v; want %v", addr, host)
}
case <-time.After(5 * time.Second):
t.Error("timed out")
}
}
// https://golang.org/issue/15960
func TestHandlerSetTransferEncodingChunked(t *testing.T) {
setParallel(t)
defer afterTest(t)
ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Transfer-Encoding", "chunked")
w.Write([]byte("hello"))
}))
resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
const hdr = "Transfer-Encoding: chunked"
if n := strings.Count(resp, hdr); n != 1 {
t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
}
}
// https://golang.org/issue/16063
func TestHandlerSetTransferEncodingGzip(t *testing.T) {
setParallel(t)
defer afterTest(t)
ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Transfer-Encoding", "gzip")
gz := gzip.NewWriter(w)
gz.Write([]byte("hello"))
gz.Close()
}))
resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
for _, v := range []string{"gzip", "chunked"} {
hdr := "Transfer-Encoding: " + v
if n := strings.Count(resp, hdr); n != 1 {
t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
}
}
}
func BenchmarkClientServer(b *testing.B) {
b.ReportAllocs()
b.StopTimer()
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
fmt.Fprintf(rw, "Hello world.\n")
}))
defer ts.Close()
b.StartTimer()
for i := 0; i < b.N; i++ {
res, err := Get(ts.URL)
if err != nil {
b.Fatal("Get:", err)
}
all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Fatal("ReadAll:", err)
}
body := string(all)
if body != "Hello world.\n" {
b.Fatal("Got body:", body)
}
}
b.StopTimer()
}
func BenchmarkClientServerParallel4(b *testing.B) {
benchmarkClientServerParallel(b, 4, false)
}
func BenchmarkClientServerParallel64(b *testing.B) {
benchmarkClientServerParallel(b, 64, false)
}
func BenchmarkClientServerParallelTLS4(b *testing.B) {
benchmarkClientServerParallel(b, 4, true)
}
func BenchmarkClientServerParallelTLS64(b *testing.B) {
benchmarkClientServerParallel(b, 64, true)
}
func benchmarkClientServerParallel(b *testing.B, parallelism int, useTLS bool) {
b.ReportAllocs()
ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
fmt.Fprintf(rw, "Hello world.\n")
}))
if useTLS {
ts.StartTLS()
} else {
ts.Start()
}
defer ts.Close()
b.ResetTimer()
b.SetParallelism(parallelism)
b.RunParallel(func(pb *testing.PB) {
c := ts.Client()
for pb.Next() {
res, err := c.Get(ts.URL)
if err != nil {
b.Logf("Get: %v", err)
continue
}
all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Logf("ReadAll: %v", err)
continue
}
body := string(all)
if body != "Hello world.\n" {
panic("Got body: " + body)
}
}
})
}
// A benchmark for profiling the server without the HTTP client code.
// The client code runs in a subprocess.
//
// For use like:
// $ go test -c
// $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof
// $ go tool pprof http.test http.prof
// (pprof) web
func BenchmarkServer(b *testing.B) {
b.ReportAllocs()
// Child process mode;
if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" {
n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N"))
if err != nil {
panic(err)
}
for i := 0; i < n; i++ {
res, err := Get(url)
if err != nil {
log.Panicf("Get: %v", err)
}
all, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Panicf("ReadAll: %v", err)
}
body := string(all)
if body != "Hello world.\n" {
log.Panicf("Got body: %q", body)
}
}
os.Exit(0)
return
}
var res = []byte("Hello world.\n")
b.StopTimer()
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Write(res)
}))
defer ts.Close()
b.StartTimer()
cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer$")
cmd.Env = append([]string{
fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N),
fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL),
}, os.Environ()...)
out, err := cmd.CombinedOutput()
if err != nil {
b.Errorf("Test failure: %v, with output: %s", err, out)
}
}
// getNoBody wraps Get but closes any Response.Body before returning the response.
func getNoBody(urlStr string) (*Response, error) {
res, err := Get(urlStr)
if err != nil {
return nil, err
}
res.Body.Close()
return res, nil
}
// A benchmark for profiling the client without the HTTP server code.
// The server code runs in a subprocess.
func BenchmarkClient(b *testing.B) {
b.ReportAllocs()
b.StopTimer()
defer afterTest(b)
var data = []byte("Hello world.\n")
if server := os.Getenv("TEST_BENCH_SERVER"); server != "" {
// Server process mode.
port := os.Getenv("TEST_BENCH_SERVER_PORT") // can be set by user
if port == "" {
port = "0"
}
ln, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
fmt.Println(ln.Addr().String())
HandleFunc("/", func(w ResponseWriter, r *Request) {
r.ParseForm()
if r.Form.Get("stop") != "" {
os.Exit(0)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
})
var srv Server
log.Fatal(srv.Serve(ln))
}
// Start server process.
cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkClient$")
cmd.Env = append(os.Environ(), "TEST_BENCH_SERVER=yes")
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
b.Fatal(err)
}
if err := cmd.Start(); err != nil {
b.Fatalf("subprocess failed to start: %v", err)
}
defer cmd.Process.Kill()
// Wait for the server in the child process to respond and tell us
// its listening address, once it's started listening:
timer := time.AfterFunc(10*time.Second, func() {
cmd.Process.Kill()
})
defer timer.Stop()
bs := bufio.NewScanner(stdout)
if !bs.Scan() {
b.Fatalf("failed to read listening URL from child: %v", bs.Err())
}
url := "http://" + strings.TrimSpace(bs.Text()) + "/"
timer.Stop()
if _, err := getNoBody(url); err != nil {
b.Fatalf("initial probe of child process failed: %v", err)
}
done := make(chan error)
stop := make(chan struct{})
defer close(stop)
go func() {
select {
case <-stop:
return
case done <- cmd.Wait():
}
}()
// Do b.N requests to the server.
b.StartTimer()
for i := 0; i < b.N; i++ {
res, err := Get(url)
if err != nil {
b.Fatalf("Get: %v", err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
b.Fatalf("ReadAll: %v", err)
}
if !bytes.Equal(body, data) {
b.Fatalf("Got body: %q", body)
}
}
b.StopTimer()
// Instruct server process to stop.
getNoBody(url + "?stop=yes")
select {
case err := <-done:
if err != nil {
b.Fatalf("subprocess failed: %v", err)
}
case <-time.After(5 * time.Second):
b.Fatalf("subprocess did not stop")
}
}
func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) {
b.ReportAllocs()
req := reqBytes(`GET / HTTP/1.0
Host: golang.org
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
`)
res := []byte("Hello world!\n")
conn := &testConn{
// testConn.Close will not push into the channel
// if it's full.
closec: make(chan bool, 1),
}
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Write(res)
})
ln := new(oneConnListener)
for i := 0; i < b.N; i++ {
conn.readBuf.Reset()
conn.writeBuf.Reset()
conn.readBuf.Write(req)
ln.conn = conn
Serve(ln, handler)
<-conn.closec
}
}
// repeatReader reads content count times, then EOFs.
type repeatReader struct {
content []byte
count int
off int
}
func (r *repeatReader) Read(p []byte) (n int, err error) {
if r.count <= 0 {
return 0, io.EOF
}
n = copy(p, r.content[r.off:])
r.off += n
if r.off == len(r.content) {
r.count--
r.off = 0
}
return
}
func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) {
b.ReportAllocs()
req := reqBytes(`GET / HTTP/1.1
Host: golang.org
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
`)
res := []byte("Hello world!\n")
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
handled++
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Write(res)
})
ln := &oneConnListener{conn: conn}
go Serve(ln, handler)
<-conn.closec
if b.N != handled {
b.Errorf("b.N=%d but handled %d", b.N, handled)
}
}
// same as above, but representing the most simple possible request
// and handler. Notably: the handler does not call rw.Header().
func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) {
b.ReportAllocs()
req := reqBytes(`GET / HTTP/1.1
Host: golang.org
`)
res := []byte("Hello world!\n")
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
handled++
rw.Write(res)
})
ln := &oneConnListener{conn: conn}
go Serve(ln, handler)
<-conn.closec
if b.N != handled {
b.Errorf("b.N=%d but handled %d", b.N, handled)
}
}
const someResponse = "<html>some response</html>"
// A Response that's just no bigger than 2KB, the buffer-before-chunking threshold.
var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse))
// Both Content-Type and Content-Length set. Should be no buffering.
func BenchmarkServerHandlerTypeLen(b *testing.B) {
benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
}))
}
// A Content-Type is set, but no length. No sniffing, but will count the Content-Length.
func BenchmarkServerHandlerNoLen(b *testing.B) {
benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/html")
w.Write(response)
}))
}
// A Content-Length is set, but the Content-Type will be sniffed.
func BenchmarkServerHandlerNoType(b *testing.B) {
benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
w.Write(response)
}))
}
// Neither a Content-Type or Content-Length, so sniffed and counted.
func BenchmarkServerHandlerNoHeader(b *testing.B) {
benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
w.Write(response)
}))
}
func benchmarkHandler(b *testing.B, h Handler) {
b.ReportAllocs()
req := reqBytes(`GET / HTTP/1.1
Host: golang.org
`)
conn := &rwTestConn{
Reader: &repeatReader{content: req, count: b.N},
Writer: io.Discard,
closec: make(chan bool, 1),
}
handled := 0
handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
handled++
h.ServeHTTP(rw, r)
})
ln := &oneConnListener{conn: conn}
go Serve(ln, handler)
<-conn.closec
if b.N != handled {
b.Errorf("b.N=%d but handled %d", b.N, handled)
}
}
func BenchmarkServerHijack(b *testing.B) {
b.ReportAllocs()
req := reqBytes(`GET / HTTP/1.1
Host: golang.org
`)
h := HandlerFunc(func(w ResponseWriter, r *Request) {
conn, _, err := w.(Hijacker).Hijack()
if err != nil {
panic(err)
}
conn.Close()
})
conn := &rwTestConn{
Writer: io.Discard,
closec: make(chan bool, 1),
}
ln := &oneConnListener{conn: conn}
for i := 0; i < b.N; i++ {
conn.Reader = bytes.NewReader(req)
ln.conn = conn
Serve(ln, h)
<-conn.closec
}
}
func BenchmarkCloseNotifier(b *testing.B) {
b.ReportAllocs()
b.StopTimer()
sawClose := make(chan bool)
ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
<-rw.(CloseNotifier).CloseNotify()
sawClose <- true
}))
defer ts.Close()
tot := time.NewTimer(5 * time.Second)
defer tot.Stop()
b.StartTimer()
for i := 0; i < b.N; i++ {
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
b.Fatalf("error dialing: %v", err)
}
_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
if err != nil {
b.Fatal(err)
}
conn.Close()
tot.Reset(5 * time.Second)
select {
case <-sawClose:
case <-tot.C:
b.Fatal("timeout")
}
}
b.StopTimer()
}
// Verify this doesn't race (Issue 16505)
func TestConcurrentServerServe(t *testing.T) {
setParallel(t)
for i := 0; i < 100; i++ {
ln1 := &oneConnListener{conn: nil}
ln2 := &oneConnListener{conn: nil}
srv := Server{}
go func() { srv.Serve(ln1) }()
go func() { srv.Serve(ln2) }()
}
}
func TestServerIdleTimeout(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
io.Copy(io.Discard, r.Body)
io.WriteString(w, r.RemoteAddr)
}))
ts.Config.ReadHeaderTimeout = 1 * time.Second
ts.Config.IdleTimeout = 2 * time.Second
ts.Start()
defer ts.Close()
c := ts.Client()
get := func() string {
res, err := c.Get(ts.URL)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return string(slurp)
}
a1, a2 := get(), get()
if a1 != a2 {
t.Fatalf("did requests on different connections")
}
time.Sleep(3 * time.Second)
a3 := get()
if a2 == a3 {
t.Fatal("request three unexpectedly on same connection")
}
// And test that ReadHeaderTimeout still works:
conn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n"))
time.Sleep(2 * time.Second)
if _, err := io.CopyN(io.Discard, conn, 1); err == nil {
t.Fatal("copy byte succeeded; want err")
}
}
func get(t *testing.T, c *Client, url string) string {
res, err := c.Get(url)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
slurp, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return string(slurp)
}
// Tests that calls to Server.SetKeepAlivesEnabled(false) closes any
// currently-open connections.
func TestServerSetKeepAlivesEnabledClosesConns(t *testing.T) {
setParallel(t)
defer afterTest(t)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
io.WriteString(w, r.RemoteAddr)
}))
defer ts.Close()
c := ts.Client()
tr := c.Transport.(*Transport)
get := func() string { return get(t, c, ts.URL) }
a1, a2 := get(), get()
if a1 != a2 {
t.Fatal("expected first two requests on same connection")
}
addr := strings.TrimPrefix(ts.URL, "http://")
// The two requests should have used the same connection,
// and there should not have been a second connection that
// was created by racing dial against reuse.
// (The first get was completed when the second get started.)
n := tr.IdleConnCountForTesting("http", addr)
if n != 1 {
t.Fatalf("idle count for %q after 2 gets = %d, want 1", addr, n)
}
// SetKeepAlivesEnabled should discard idle conns.
ts.Config.SetKeepAlivesEnabled(false)
var idle1 int
if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
idle1 = tr.IdleConnCountForTesting("http", addr)
return idle1 == 0
}) {
t.Fatalf("idle count after SetKeepAlivesEnabled called = %v; want 0", idle1)
}
a3 := get()
if a3 == a2 {
t.Fatal("expected third request on new connection")
}
}
func TestServerShutdown_h1(t *testing.T) {
testServerShutdown(t, h1Mode)
}
func TestServerShutdown_h2(t *testing.T) {
testServerShutdown(t, h2Mode)
}
func testServerShutdown(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
var doShutdown func() // set later
var doStateCount func()
var shutdownRes = make(chan error, 1)
var statesRes = make(chan map[ConnState]int, 1)
var gotOnShutdown = make(chan struct{}, 1)
handler := HandlerFunc(func(w ResponseWriter, r *Request) {
doStateCount()
go doShutdown()
// Shutdown is graceful, so it should not interrupt
// this in-flight response. Add a tiny sleep here to
// increase the odds of a failure if shutdown has
// bugs.
time.Sleep(20 * time.Millisecond)
io.WriteString(w, r.RemoteAddr)
})
cst := newClientServerTest(t, h2, handler, func(srv *httptest.Server) {
srv.Config.RegisterOnShutdown(func() { gotOnShutdown <- struct{}{} })
})
defer cst.close()
doShutdown = func() {
shutdownRes <- cst.ts.Config.Shutdown(context.Background())
}
doStateCount = func() {
statesRes <- cst.ts.Config.ExportAllConnsByState()
}
get(t, cst.c, cst.ts.URL) // calls t.Fail on failure
if err := <-shutdownRes; err != nil {
t.Fatalf("Shutdown: %v", err)
}
select {
case <-gotOnShutdown:
case <-time.After(5 * time.Second):
t.Errorf("onShutdown callback not called, RegisterOnShutdown broken?")
}
if states := <-statesRes; states[StateActive] != 1 {
t.Errorf("connection in wrong state, %v", states)
}
res, err := cst.c.Get(cst.ts.URL)
if err == nil {
res.Body.Close()
t.Fatal("second request should fail. server should be shut down")
}
}
func TestServerShutdownStateNew(t *testing.T) {
if testing.Short() {
t.Skip("test takes 5-6 seconds; skipping in short mode")
}
setParallel(t)
defer afterTest(t)
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
// nothing.
}))
var connAccepted sync.WaitGroup
ts.Config.ConnState = func(conn net.Conn, state ConnState) {
if state == StateNew {
connAccepted.Done()
}
}
ts.Start()
defer ts.Close()
// Start a connection but never write to it.
connAccepted.Add(1)
c, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer c.Close()
// Wait for the connection to be accepted by the server. Otherwise, if
// Shutdown happens to run first, the server will be closed when
// encountering the connection, in which case it will be rejected
// immediately.
connAccepted.Wait()
shutdownRes := make(chan error, 1)
go func() {
shutdownRes <- ts.Config.Shutdown(context.Background())
}()
readRes := make(chan error, 1)
go func() {
_, err := c.Read([]byte{0})
readRes <- err
}()
const expectTimeout = 5 * time.Second
t0 := time.Now()
select {
case got := <-shutdownRes:
d := time.Since(t0)
if got != nil {
t.Fatalf("shutdown error after %v: %v", d, err)
}
if d < expectTimeout/2 {
t.Errorf("shutdown too soon after %v", d)
}
case <-time.After(expectTimeout * 3 / 2):
t.Fatalf("timeout waiting for shutdown")
}
// Wait for c.Read to unblock; should be already done at this point,
// or within a few milliseconds.
select {
case err := <-readRes:
if err == nil {
t.Error("expected error from Read")
}
case <-time.After(2 * time.Second):
t.Errorf("timeout waiting for Read to unblock")
}
}
// Issue 17878: tests that we can call Close twice.
func TestServerCloseDeadlock(t *testing.T) {
var s Server
s.Close()
s.Close()
}
// Issue 17717: tests that Server.SetKeepAlivesEnabled is respected by
// both HTTP/1 and HTTP/2.
func TestServerKeepAlivesEnabled_h1(t *testing.T) { testServerKeepAlivesEnabled(t, h1Mode) }
func TestServerKeepAlivesEnabled_h2(t *testing.T) { testServerKeepAlivesEnabled(t, h2Mode) }
func testServerKeepAlivesEnabled(t *testing.T, h2 bool) {
if h2 {
restore := ExportSetH2GoawayTimeout(10 * time.Millisecond)
defer restore()
}
// Not parallel: messes with global variable. (http2goAwayTimeout)
defer afterTest(t)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "%v", r.RemoteAddr)
}))
defer cst.close()
srv := cst.ts.Config
srv.SetKeepAlivesEnabled(false)
a := cst.getURL(cst.ts.URL)
if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
t.Fatalf("test server has active conns")
}
b := cst.getURL(cst.ts.URL)
if a == b {
t.Errorf("got same connection between first and second requests")
}
if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
t.Fatalf("test server has active conns")
}
}
// Issue 18447: test that the Server's ReadTimeout is stopped while
// the server's doing its 1-byte background read between requests,
// waiting for the connection to maybe close.
func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) {
setParallel(t)
defer afterTest(t)
runTimeSensitiveTest(t, []time.Duration{
10 * time.Millisecond,
50 * time.Millisecond,
250 * time.Millisecond,
time.Second,
2 * time.Second,
}, func(t *testing.T, timeout time.Duration) error {
ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
select {
case <-time.After(2 * timeout):
fmt.Fprint(w, "ok")
case <-r.Context().Done():
fmt.Fprint(w, r.Context().Err())
}
}))
ts.Config.ReadTimeout = timeout
ts.Start()
defer ts.Close()
c := ts.Client()
res, err := c.Get(ts.URL)
if err != nil {
return fmt.Errorf("Get: %v", err)
}
slurp, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return fmt.Errorf("Body ReadAll: %v", err)
}
if string(slurp) != "ok" {
return fmt.Errorf("got: %q, want ok", slurp)
}
return nil
})
}
// runTimeSensitiveTest runs test with the provided durations until one passes.
// If they all fail, t.Fatal is called with the last one's duration and error value.
func runTimeSensitiveTest(t *testing.T, durations []time.Duration, test func(t *testing.T, d time.Duration) error) {
for i, d := range durations {
err := test(t, d)
if err == nil {
return
}
if i == len(durations)-1 {
t.Fatalf("failed with duration %v: %v", d, err)
}
}
}
// Issue 18535: test that the Server doesn't try to do a background
// read if it's already done one.
func TestServerDuplicateBackgroundRead(t *testing.T) {
if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm" {
testenv.SkipFlaky(t, 24826)
}
setParallel(t)
defer afterTest(t)
goroutines := 5
requests := 2000
if testing.Short() {
goroutines = 3
requests = 100
}
hts := httptest.NewServer(HandlerFunc(NotFound))
defer hts.Close()
reqBytes := []byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")
var wg sync.WaitGroup
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
cn, err := net.Dial("tcp", hts.Listener.Addr().String())
if err != nil {
t.Error(err)
return
}
defer cn.Close()
wg.Add(1)
go func() {
defer wg.Done()
io.Copy(io.Discard, cn)
}()
for j := 0; j < requests; j++ {
if t.Failed() {
return
}
_, err := cn.Write(reqBytes)
if err != nil {
t.Error(err)
return
}
}
}()
}
wg.Wait()
}
// Test that the bufio.Reader returned by Hijack includes any buffered
// byte (from the Server's backgroundRead) in its buffer. We want the
// Handler code to be able to tell that a byte is available via
// bufio.Reader.Buffered(), without resorting to Reading it
// (potentially blocking) to get at it.
func TestServerHijackGetsBackgroundByte(t *testing.T) {
if runtime.GOOS == "plan9" {
t.Skip("skipping test; see https://golang.org/issue/18657")
}
setParallel(t)
defer afterTest(t)
done := make(chan struct{})
inHandler := make(chan bool, 1)
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
defer close(done)
// Tell the client to send more data after the GET request.
inHandler <- true
conn, buf, err := w.(Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
defer conn.Close()
peek, err := buf.Reader.Peek(3)
if string(peek) != "foo" || err != nil {
t.Errorf("Peek = %q, %v; want foo, nil", peek, err)
}
select {
case <-r.Context().Done():
t.Error("context unexpectedly canceled")
default:
}
}))
defer ts.Close()
cn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer cn.Close()
if _, err := cn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil {
t.Fatal(err)
}
<-inHandler
if _, err := cn.Write([]byte("foo")); err != nil {
t.Fatal(err)
}
if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Error("timeout")
}
}
// Like TestServerHijackGetsBackgroundByte above but sending a
// immediate 1MB of data to the server to fill up the server's 4KB
// buffer.
func TestServerHijackGetsBackgroundByte_big(t *testing.T) {
if runtime.GOOS == "plan9" {
t.Skip("skipping test; see https://golang.org/issue/18657")
}
setParallel(t)
defer afterTest(t)
done := make(chan struct{})
const size = 8 << 10
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
defer close(done)
conn, buf, err := w.(Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
defer conn.Close()
slurp, err := io.ReadAll(buf.Reader)
if err != nil {
t.Errorf("Copy: %v", err)
}
allX := true
for _, v := range slurp {
if v != 'x' {
allX = false
}
}
if len(slurp) != size {
t.Errorf("read %d; want %d", len(slurp), size)
} else if !allX {
t.Errorf("read %q; want %d 'x'", slurp, size)
}
}))
defer ts.Close()
cn, err := net.Dial("tcp", ts.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer cn.Close()
if _, err := fmt.Fprintf(cn, "GET / HTTP/1.1\r\nHost: e.com\r\n\r\n%s",
strings.Repeat("x", size)); err != nil {
t.Fatal(err)
}
if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Error("timeout")
}
}
// Issue 18319: test that the Server validates the request method.
func TestServerValidatesMethod(t *testing.T) {
tests := []struct {
method string
want int
}{
{"GET", 200},
{"GE(T", 400},
}
for _, tt := range tests {
conn := &testConn{closec: make(chan bool, 1)}
io.WriteString(&conn.readBuf, tt.method+" / HTTP/1.1\r\nHost: foo.example\r\n\r\n")
ln := &oneConnListener{conn}
go Serve(ln, serve(200))
<-conn.closec
res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
if err != nil {
t.Errorf("For %s, ReadResponse: %v", tt.method, res)
continue
}
if res.StatusCode != tt.want {
t.Errorf("For %s, Status = %d; want %d", tt.method, res.StatusCode, tt.want)
}
}
}
// Listener for TestServerListenNotComparableListener.
type eofListenerNotComparable []int
func (eofListenerNotComparable) Accept() (net.Conn, error) { return nil, io.EOF }
func (eofListenerNotComparable) Addr() net.Addr { return nil }
func (eofListenerNotComparable) Close() error { return nil }
// Issue 24812: don't crash on non-comparable Listener
func TestServerListenNotComparableListener(t *testing.T) {
var s Server
s.Serve(make(eofListenerNotComparable, 1)) // used to panic
}
// countCloseListener is a Listener wrapper that counts the number of Close calls.
type countCloseListener struct {
net.Listener
closes int32 // atomic
}
func (p *countCloseListener) Close() error {
var err error
if n := atomic.AddInt32(&p.closes, 1); n == 1 && p.Listener != nil {
err = p.Listener.Close()
}
return err
}
// Issue 24803: don't call Listener.Close on Server.Shutdown.
func TestServerCloseListenerOnce(t *testing.T) {
setParallel(t)
defer afterTest(t)
ln := newLocalListener(t)
defer ln.Close()
cl := &countCloseListener{Listener: ln}
server := &Server{}
sdone := make(chan bool, 1)
go func() {
server.Serve(cl)
sdone <- true
}()
time.Sleep(10 * time.Millisecond)
server.Shutdown(context.Background())
ln.Close()
<-sdone
nclose := atomic.LoadInt32(&cl.closes)
if nclose != 1 {
t.Errorf("Close calls = %v; want 1", nclose)
}
}
// Issue 20239: don't block in Serve if Shutdown is called first.
func TestServerShutdownThenServe(t *testing.T) {
var srv Server
cl := &countCloseListener{Listener: nil}
srv.Shutdown(context.Background())
got := srv.Serve(cl)
if got != ErrServerClosed {
t.Errorf("Serve err = %v; want ErrServerClosed", got)
}
nclose := atomic.LoadInt32(&cl.closes)
if nclose != 1 {
t.Errorf("Close calls = %v; want 1", nclose)
}
}
// Issue 23351: document and test behavior of ServeMux with ports
func TestStripPortFromHost(t *testing.T) {
mux := NewServeMux()
mux.HandleFunc("example.com/", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "OK")
})
mux.HandleFunc("example.com:9000/", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "uh-oh!")
})
req := httptest.NewRequest("GET", "http://example.com:9000/", nil)
rw := httptest.NewRecorder()
mux.ServeHTTP(rw, req)
response := rw.Body.String()
if response != "OK" {
t.Errorf("Response gotten was %q", response)
}
}
func TestServerContexts(t *testing.T) {
setParallel(t)
defer afterTest(t)
type baseKey struct{}
type connKey struct{}
ch := make(chan context.Context, 1)
ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
ch <- r.Context()
}))
ts.Config.BaseContext = func(ln net.Listener) context.Context {
if strings.Contains(reflect.TypeOf(ln).String(), "onceClose") {
t.Errorf("unexpected onceClose listener type %T", ln)
}
return context.WithValue(context.Background(), baseKey{}, "base")
}
ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
if got, want := ctx.Value(baseKey{}), "base"; got != want {
t.Errorf("in ConnContext, base context key = %#v; want %q", got, want)
}
return context.WithValue(ctx, connKey{}, "conn")
}
ts.Start()
defer ts.Close()
res, err := ts.Client().Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
ctx := <-ch
if got, want := ctx.Value(baseKey{}), "base"; got != want {
t.Errorf("base context key = %#v; want %q", got, want)
}
if got, want := ctx.Value(connKey{}), "conn"; got != want {
t.Errorf("conn context key = %#v; want %q", got, want)
}
}
func TestServerContextsHTTP2(t *testing.T) {
setParallel(t)
defer afterTest(t)
type baseKey struct{}
type connKey struct{}
ch := make(chan context.Context, 1)
ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
if r.ProtoMajor != 2 {
t.Errorf("unexpected HTTP/1.x request")
}
ch <- r.Context()
}))
ts.Config.BaseContext = func(ln net.Listener) context.Context {
if strings.Contains(reflect.TypeOf(ln).String(), "onceClose") {
t.Errorf("unexpected onceClose listener type %T", ln)
}
return context.WithValue(context.Background(), baseKey{}, "base")
}
ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
if got, want := ctx.Value(baseKey{}), "base"; got != want {
t.Errorf("in ConnContext, base context key = %#v; want %q", got, want)
}
return context.WithValue(ctx, connKey{}, "conn")
}
ts.TLS = &tls.Config{
NextProtos: []string{"h2", "http/1.1"},
}
ts.StartTLS()
defer ts.Close()
ts.Client().Transport.(*Transport).ForceAttemptHTTP2 = true
res, err := ts.Client().Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
ctx := <-ch
if got, want := ctx.Value(baseKey{}), "base"; got != want {
t.Errorf("base context key = %#v; want %q", got, want)
}
if got, want := ctx.Value(connKey{}), "conn"; got != want {
t.Errorf("conn context key = %#v; want %q", got, want)
}
}
// Issue 35750: check ConnContext not modifying context for other connections
func TestConnContextNotModifyingAllContexts(t *testing.T) {
setParallel(t)
defer afterTest(t)
type connKey struct{}
ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
rw.Header().Set("Connection", "close")
}))
ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
if got := ctx.Value(connKey{}); got != nil {
t.Errorf("in ConnContext, unexpected context key = %#v", got)
}
return context.WithValue(ctx, connKey{}, "conn")
}
ts.Start()
defer ts.Close()
var res *Response
var err error
res, err = ts.Client().Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
res, err = ts.Client().Get(ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
}
// Issue 30710: ensure that as per the spec, a server responds
// with 501 Not Implemented for unsupported transfer-encodings.
func TestUnsupportedTransferEncodingsReturn501(t *testing.T) {
cst := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Write([]byte("Hello, World!"))
}))
defer cst.Close()
serverURL, err := url.Parse(cst.URL)
if err != nil {
t.Fatalf("Failed to parse server URL: %v", err)
}
unsupportedTEs := []string{
"fugazi",
"foo-bar",
"unknown",
}
for _, badTE := range unsupportedTEs {
http1ReqBody := fmt.Sprintf(""+
"POST / HTTP/1.1\r\nConnection: close\r\n"+
"Host: localhost\r\nTransfer-Encoding: %s\r\n\r\n", badTE)
gotBody, err := fetchWireResponse(serverURL.Host, []byte(http1ReqBody))
if err != nil {
t.Errorf("%q. unexpected error: %v", badTE, err)
continue
}
wantBody := fmt.Sprintf("" +
"HTTP/1.1 501 Not Implemented\r\nContent-Type: text/plain; charset=utf-8\r\n" +
"Connection: close\r\n\r\nUnsupported transfer encoding")
if string(gotBody) != wantBody {
t.Errorf("%q. body\ngot\n%q\nwant\n%q", badTE, gotBody, wantBody)
}
}
}
func TestContentEncodingNoSniffing_h1(t *testing.T) {
testContentEncodingNoSniffing(t, h1Mode)
}
func TestContentEncodingNoSniffing_h2(t *testing.T) {
testContentEncodingNoSniffing(t, h2Mode)
}
// Issue 31753: don't sniff when Content-Encoding is set
func testContentEncodingNoSniffing(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
type setting struct {
name string
body []byte
// setting contentEncoding as an interface instead of a string
// directly, so as to differentiate between 3 states:
// unset, empty string "" and set string "foo/bar".
contentEncoding interface{}
wantContentType string
}
settings := []*setting{
{
name: "gzip content-encoding, gzipped", // don't sniff.
contentEncoding: "application/gzip",
wantContentType: "",
body: func() []byte {
buf := new(bytes.Buffer)
gzw := gzip.NewWriter(buf)
gzw.Write([]byte("doctype html><p>Hello</p>"))
gzw.Close()
return buf.Bytes()
}(),
},
{
name: "zlib content-encoding, zlibbed", // don't sniff.
contentEncoding: "application/zlib",
wantContentType: "",
body: func() []byte {
buf := new(bytes.Buffer)
zw := zlib.NewWriter(buf)
zw.Write([]byte("doctype html><p>Hello</p>"))
zw.Close()
return buf.Bytes()
}(),
},
{
name: "no content-encoding", // must sniff.
wantContentType: "application/x-gzip",
body: func() []byte {
buf := new(bytes.Buffer)
gzw := gzip.NewWriter(buf)
gzw.Write([]byte("doctype html><p>Hello</p>"))
gzw.Close()
return buf.Bytes()
}(),
},
{
name: "phony content-encoding", // don't sniff.
contentEncoding: "foo/bar",
body: []byte("doctype html><p>Hello</p>"),
},
{
name: "empty but set content-encoding",
contentEncoding: "",
wantContentType: "audio/mpeg",
body: []byte("ID3"),
},
}
for _, tt := range settings {
t.Run(tt.name, func(t *testing.T) {
cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
if tt.contentEncoding != nil {
rw.Header().Set("Content-Encoding", tt.contentEncoding.(string))
}
rw.Write(tt.body)
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatalf("Failed to fetch URL: %v", err)
}
defer res.Body.Close()
if g, w := res.Header.Get("Content-Encoding"), tt.contentEncoding; g != w {
if w != nil { // The case where contentEncoding was set explicitly.
t.Errorf("Content-Encoding mismatch\n\tgot: %q\n\twant: %q", g, w)
} else if g != "" { // "" should be the equivalent when the contentEncoding is unset.
t.Errorf("Unexpected Content-Encoding %q", g)
}
}
if g, w := res.Header.Get("Content-Type"), tt.wantContentType; g != w {
t.Errorf("Content-Type mismatch\n\tgot: %q\n\twant: %q", g, w)
}
})
}
}
// Issue 30803: ensure that TimeoutHandler logs spurious
// WriteHeader calls, for consistency with other Handlers.
func TestTimeoutHandlerSuperfluousLogs(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
pc, curFile, _, _ := runtime.Caller(0)
curFileBaseName := filepath.Base(curFile)
testFuncName := runtime.FuncForPC(pc).Name()
timeoutMsg := "timed out here!"
tests := []struct {
name string
mustTimeout bool
wantResp string
}{
{
name: "return before timeout",
wantResp: "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n",
},
{
name: "return after timeout",
mustTimeout: true,
wantResp: fmt.Sprintf("HTTP/1.1 503 Service Unavailable\r\nContent-Length: %d\r\n\r\n%s",
len(timeoutMsg), timeoutMsg),
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
exitHandler := make(chan bool, 1)
defer close(exitHandler)
lastLine := make(chan int, 1)
sh := HandlerFunc(func(w ResponseWriter, r *Request) {
w.WriteHeader(404)
w.WriteHeader(404)
w.WriteHeader(404)
w.WriteHeader(404)
_, _, line, _ := runtime.Caller(0)
lastLine <- line
<-exitHandler
})
if !tt.mustTimeout {
exitHandler <- true
}
logBuf := new(bytes.Buffer)
srvLog := log.New(logBuf, "", 0)
// When expecting to timeout, we'll keep the duration short.
dur := 20 * time.Millisecond
if !tt.mustTimeout {
// Otherwise, make it arbitrarily long to reduce the risk of flakes.
dur = 10 * time.Second
}
th := TimeoutHandler(sh, dur, timeoutMsg)
cst := newClientServerTest(t, h1Mode /* the test is protocol-agnostic */, th, optWithServerLog(srvLog))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Deliberately removing the "Date" header since it is highly ephemeral
// and will cause failure if we try to match it exactly.
res.Header.Del("Date")
res.Header.Del("Content-Type")
// Match the response.
blob, _ := httputil.DumpResponse(res, true)
if g, w := string(blob), tt.wantResp; g != w {
t.Errorf("Response mismatch\nGot\n%q\n\nWant\n%q", g, w)
}
// Given 4 w.WriteHeader calls, only the first one is valid
// and the rest should be reported as the 3 spurious logs.
logEntries := strings.Split(strings.TrimSpace(logBuf.String()), "\n")
if g, w := len(logEntries), 3; g != w {
blob, _ := json.MarshalIndent(logEntries, "", " ")
t.Fatalf("Server logs count mismatch\ngot %d, want %d\n\nGot\n%s\n", g, w, blob)
}
lastSpuriousLine := <-lastLine
firstSpuriousLine := lastSpuriousLine - 3
// Now ensure that the regexes match exactly.
// "http: superfluous response.WriteHeader call from <fn>.func\d.\d (<curFile>:lastSpuriousLine-[1, 3]"
for i, logEntry := range logEntries {
wantLine := firstSpuriousLine + i
pat := fmt.Sprintf("^http: superfluous response.WriteHeader call from %s.func\\d+.\\d+ \\(%s:%d\\)$",
testFuncName, curFileBaseName, wantLine)
re := regexp.MustCompile(pat)
if !re.MatchString(logEntry) {
t.Errorf("Log entry mismatch\n\t%s\ndoes not match\n\t%s", logEntry, pat)
}
}
})
}
}
// fetchWireResponse is a helper for dialing to host,
// sending http1ReqBody as the payload and retrieving
// the response as it was sent on the wire.
func fetchWireResponse(host string, http1ReqBody []byte) ([]byte, error) {
conn, err := net.Dial("tcp", host)
if err != nil {
return nil, err
}
defer conn.Close()
if _, err := conn.Write(http1ReqBody); err != nil {
return nil, err
}
return io.ReadAll(conn)
}
func BenchmarkResponseStatusLine(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
bw := bufio.NewWriter(io.Discard)
var buf3 [3]byte
for pb.Next() {
Export_writeStatusLine(bw, true, 200, buf3[:])
}
})
}
func TestDisableKeepAliveUpgrade(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
setParallel(t)
defer afterTest(t)
s := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Connection", "Upgrade")
w.Header().Set("Upgrade", "someProto")
w.WriteHeader(StatusSwitchingProtocols)
c, buf, err := w.(Hijacker).Hijack()
if err != nil {
return
}
defer c.Close()
// Copy from the *bufio.ReadWriter, which may contain buffered data.
// Copy to the net.Conn, to avoid buffering the output.
io.Copy(c, buf)
}))
s.Config.SetKeepAlivesEnabled(false)
s.Start()
defer s.Close()
cl := s.Client()
cl.Transport.(*Transport).DisableKeepAlives = true
resp, err := cl.Get(s.URL)
if err != nil {
t.Fatalf("failed to perform request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != StatusSwitchingProtocols {
t.Fatalf("unexpected status code: %v", resp.StatusCode)
}
rwc, ok := resp.Body.(io.ReadWriteCloser)
if !ok {
t.Fatalf("Response.Body is not a io.ReadWriteCloser: %T", resp.Body)
}
_, err = rwc.Write([]byte("hello"))
if err != nil {
t.Fatalf("failed to write to body: %v", err)
}
b := make([]byte, 5)
_, err = io.ReadFull(rwc, b)
if err != nil {
t.Fatalf("failed to read from body: %v", err)
}
if string(b) != "hello" {
t.Fatalf("unexpected value read from body:\ngot: %q\nwant: %q", b, "hello")
}
}
|