summaryrefslogtreecommitdiff
path: root/devdocs/go/net%2Fhttp%2Findex.html
blob: c5ca9625917f60ff0f254b6b923d597bd0ef0c40 (plain)
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
<h1> Package http  </h1>     <ul id="short-nav">
<li><code>import "net/http"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
<li><a href="#pkg-subdirectories">Subdirectories</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package http provides HTTP client and server implementations. </p>
<p><a href="#Get">Get</a>, <a href="#Head">Head</a>, <a href="#Post">Post</a>, and <a href="#PostForm">PostForm</a> make HTTP (or HTTPS) requests: </p>
<pre data-language="go">resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &amp;buf)
...
resp, err := http.PostForm("http://example.com/form",
	url.Values{"key": {"Value"}, "id": {"123"}})
</pre> <p>The caller must close the response body when finished with it: </p>
<pre data-language="go">resp, err := http.Get("http://example.com/")
if err != nil {
	// handle error
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
// ...
</pre> <h3 id="hdr-Clients_and_Transports">Clients and Transports</h3> <p>For control over HTTP client headers, redirect policy, and other settings, create a <a href="#Client">Client</a>: </p>
<pre data-language="go">client := &amp;http.Client{
	CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
</pre> <p>For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a <a href="#Transport">Transport</a>: </p>
<pre data-language="go">tr := &amp;http.Transport{
	MaxIdleConns:       10,
	IdleConnTimeout:    30 * time.Second,
	DisableCompression: true,
}
client := &amp;http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
</pre> <p>Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used. </p>
<h3 id="hdr-Servers">Servers</h3> <p>ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use <a href="#DefaultServeMux">DefaultServeMux</a>. <a href="#Handle">Handle</a> and <a href="#HandleFunc">HandleFunc</a> add handlers to <a href="#DefaultServeMux">DefaultServeMux</a>: </p>
<pre data-language="go">http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))
</pre> <p>More control over the server's behavior is available by creating a custom Server: </p>
<pre data-language="go">s := &amp;http.Server{
	Addr:           ":8080",
	Handler:        myHandler,
	ReadTimeout:    10 * time.Second,
	WriteTimeout:   10 * time.Second,
	MaxHeaderBytes: 1 &lt;&lt; 20,
}
log.Fatal(s.ListenAndServe())
</pre> <h3 id="hdr-HTTP_2">HTTP/2</h3> <p>Starting with Go 1.6, the http package has transparent support for the HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 can do so by setting [Transport.TLSNextProto] (for clients) or [Server.TLSNextProto] (for servers) to a non-nil, empty map. Alternatively, the following GODEBUG settings are currently supported: </p>
<pre data-language="go">GODEBUG=http2client=0  # disable HTTP/2 client support
GODEBUG=http2server=0  # disable HTTP/2 server support
GODEBUG=http2debug=1   # enable verbose HTTP/2 debug logs
GODEBUG=http2debug=2   # ... even more verbose, with frame dumps
</pre> <p>Please report any issues before disabling HTTP/2 support: <a href="https://golang.org/s/http2bug">https://golang.org/s/http2bug</a> </p>
<p>The http package's <a href="#Transport">Transport</a> and <a href="#Server">Server</a> both automatically enable HTTP/2 support for simple configurations. To enable HTTP/2 for more complex configurations, to use lower-level HTTP/2 features, or to use a newer version of Go's http2 package, import "golang.org/x/net/http2" directly and use its ConfigureTransport and/or ConfigureServer functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 package takes precedence over the net/http package's built-in HTTP/2 support. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-constants">Constants</a></li>
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#CanonicalHeaderKey">func CanonicalHeaderKey(s string) string</a></li>
<li><a href="#DetectContentType">func DetectContentType(data []byte) string</a></li>
<li><a href="#Error">func Error(w ResponseWriter, error string, code int)</a></li>
<li><a href="#Handle">func Handle(pattern string, handler Handler)</a></li>
<li><a href="#HandleFunc">func HandleFunc(pattern string, handler func(ResponseWriter, *Request))</a></li>
<li><a href="#ListenAndServe">func ListenAndServe(addr string, handler Handler) error</a></li>
<li><a href="#ListenAndServeTLS">func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error</a></li>
<li><a href="#MaxBytesReader">func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser</a></li>
<li><a href="#NotFound">func NotFound(w ResponseWriter, r *Request)</a></li>
<li><a href="#ParseHTTPVersion">func ParseHTTPVersion(vers string) (major, minor int, ok bool)</a></li>
<li><a href="#ParseTime">func ParseTime(text string) (t time.Time, err error)</a></li>
<li><a href="#ProxyFromEnvironment">func ProxyFromEnvironment(req *Request) (*url.URL, error)</a></li>
<li><a href="#ProxyURL">func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)</a></li>
<li><a href="#Redirect">func Redirect(w ResponseWriter, r *Request, url string, code int)</a></li>
<li><a href="#Serve">func Serve(l net.Listener, handler Handler) error</a></li>
<li><a href="#ServeContent">func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)</a></li>
<li><a href="#ServeFile">func ServeFile(w ResponseWriter, r *Request, name string)</a></li>
<li><a href="#ServeFileFS">func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)</a></li>
<li><a href="#ServeTLS">func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error</a></li>
<li><a href="#SetCookie">func SetCookie(w ResponseWriter, cookie *Cookie)</a></li>
<li><a href="#StatusText">func StatusText(code int) string</a></li>
<li><a href="#Client">type Client</a></li>
<li> <a href="#Client.CloseIdleConnections">func (c *Client) CloseIdleConnections()</a>
</li>
<li> <a href="#Client.Do">func (c *Client) Do(req *Request) (*Response, error)</a>
</li>
<li> <a href="#Client.Get">func (c *Client) Get(url string) (resp *Response, err error)</a>
</li>
<li> <a href="#Client.Head">func (c *Client) Head(url string) (resp *Response, err error)</a>
</li>
<li> <a href="#Client.Post">func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)</a>
</li>
<li> <a href="#Client.PostForm">func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)</a>
</li>
<li><a href="#CloseNotifier">type CloseNotifier</a></li>
<li><a href="#ConnState">type ConnState</a></li>
<li> <a href="#ConnState.String">func (c ConnState) String() string</a>
</li>
<li><a href="#Cookie">type Cookie</a></li>
<li> <a href="#Cookie.String">func (c *Cookie) String() string</a>
</li>
<li> <a href="#Cookie.Valid">func (c *Cookie) Valid() error</a>
</li>
<li><a href="#CookieJar">type CookieJar</a></li>
<li><a href="#Dir">type Dir</a></li>
<li> <a href="#Dir.Open">func (d Dir) Open(name string) (File, error)</a>
</li>
<li><a href="#File">type File</a></li>
<li><a href="#FileSystem">type FileSystem</a></li>
<li> <a href="#FS">func FS(fsys fs.FS) FileSystem</a>
</li>
<li><a href="#Flusher">type Flusher</a></li>
<li><a href="#Handler">type Handler</a></li>
<li> <a href="#AllowQuerySemicolons">func AllowQuerySemicolons(h Handler) Handler</a>
</li>
<li> <a href="#FileServer">func FileServer(root FileSystem) Handler</a>
</li>
<li> <a href="#FileServerFS">func FileServerFS(root fs.FS) Handler</a>
</li>
<li> <a href="#MaxBytesHandler">func MaxBytesHandler(h Handler, n int64) Handler</a>
</li>
<li> <a href="#NotFoundHandler">func NotFoundHandler() Handler</a>
</li>
<li> <a href="#RedirectHandler">func RedirectHandler(url string, code int) Handler</a>
</li>
<li> <a href="#StripPrefix">func StripPrefix(prefix string, h Handler) Handler</a>
</li>
<li> <a href="#TimeoutHandler">func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler</a>
</li>
<li><a href="#HandlerFunc">type HandlerFunc</a></li>
<li> <a href="#HandlerFunc.ServeHTTP">func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)</a>
</li>
<li><a href="#Header">type Header</a></li>
<li> <a href="#Header.Add">func (h Header) Add(key, value string)</a>
</li>
<li> <a href="#Header.Clone">func (h Header) Clone() Header</a>
</li>
<li> <a href="#Header.Del">func (h Header) Del(key string)</a>
</li>
<li> <a href="#Header.Get">func (h Header) Get(key string) string</a>
</li>
<li> <a href="#Header.Set">func (h Header) Set(key, value string)</a>
</li>
<li> <a href="#Header.Values">func (h Header) Values(key string) []string</a>
</li>
<li> <a href="#Header.Write">func (h Header) Write(w io.Writer) error</a>
</li>
<li> <a href="#Header.WriteSubset">func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error</a>
</li>
<li><a href="#Hijacker">type Hijacker</a></li>
<li><a href="#MaxBytesError">type MaxBytesError</a></li>
<li> <a href="#MaxBytesError.Error">func (e *MaxBytesError) Error() string</a>
</li>
<li><a href="#ProtocolError">type ProtocolError</a></li>
<li> <a href="#ProtocolError.Error">func (pe *ProtocolError) Error() string</a>
</li>
<li> <a href="#ProtocolError.Is">func (pe *ProtocolError) Is(err error) bool</a>
</li>
<li><a href="#PushOptions">type PushOptions</a></li>
<li><a href="#Pusher">type Pusher</a></li>
<li><a href="#Request">type Request</a></li>
<li> <a href="#NewRequest">func NewRequest(method, url string, body io.Reader) (*Request, error)</a>
</li>
<li> <a href="#NewRequestWithContext">func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)</a>
</li>
<li> <a href="#ReadRequest">func ReadRequest(b *bufio.Reader) (*Request, error)</a>
</li>
<li> <a href="#Request.AddCookie">func (r *Request) AddCookie(c *Cookie)</a>
</li>
<li> <a href="#Request.BasicAuth">func (r *Request) BasicAuth() (username, password string, ok bool)</a>
</li>
<li> <a href="#Request.Clone">func (r *Request) Clone(ctx context.Context) *Request</a>
</li>
<li> <a href="#Request.Context">func (r *Request) Context() context.Context</a>
</li>
<li> <a href="#Request.Cookie">func (r *Request) Cookie(name string) (*Cookie, error)</a>
</li>
<li> <a href="#Request.Cookies">func (r *Request) Cookies() []*Cookie</a>
</li>
<li> <a href="#Request.FormFile">func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)</a>
</li>
<li> <a href="#Request.FormValue">func (r *Request) FormValue(key string) string</a>
</li>
<li> <a href="#Request.MultipartReader">func (r *Request) MultipartReader() (*multipart.Reader, error)</a>
</li>
<li> <a href="#Request.ParseForm">func (r *Request) ParseForm() error</a>
</li>
<li> <a href="#Request.ParseMultipartForm">func (r *Request) ParseMultipartForm(maxMemory int64) error</a>
</li>
<li> <a href="#Request.PathValue">func (r *Request) PathValue(name string) string</a>
</li>
<li> <a href="#Request.PostFormValue">func (r *Request) PostFormValue(key string) string</a>
</li>
<li> <a href="#Request.ProtoAtLeast">func (r *Request) ProtoAtLeast(major, minor int) bool</a>
</li>
<li> <a href="#Request.Referer">func (r *Request) Referer() string</a>
</li>
<li> <a href="#Request.SetBasicAuth">func (r *Request) SetBasicAuth(username, password string)</a>
</li>
<li> <a href="#Request.SetPathValue">func (r *Request) SetPathValue(name, value string)</a>
</li>
<li> <a href="#Request.UserAgent">func (r *Request) UserAgent() string</a>
</li>
<li> <a href="#Request.WithContext">func (r *Request) WithContext(ctx context.Context) *Request</a>
</li>
<li> <a href="#Request.Write">func (r *Request) Write(w io.Writer) error</a>
</li>
<li> <a href="#Request.WriteProxy">func (r *Request) WriteProxy(w io.Writer) error</a>
</li>
<li><a href="#Response">type Response</a></li>
<li> <a href="#Get">func Get(url string) (resp *Response, err error)</a>
</li>
<li> <a href="#Head">func Head(url string) (resp *Response, err error)</a>
</li>
<li> <a href="#Post">func Post(url, contentType string, body io.Reader) (resp *Response, err error)</a>
</li>
<li> <a href="#PostForm">func PostForm(url string, data url.Values) (resp *Response, err error)</a>
</li>
<li> <a href="#ReadResponse">func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)</a>
</li>
<li> <a href="#Response.Cookies">func (r *Response) Cookies() []*Cookie</a>
</li>
<li> <a href="#Response.Location">func (r *Response) Location() (*url.URL, error)</a>
</li>
<li> <a href="#Response.ProtoAtLeast">func (r *Response) ProtoAtLeast(major, minor int) bool</a>
</li>
<li> <a href="#Response.Write">func (r *Response) Write(w io.Writer) error</a>
</li>
<li><a href="#ResponseController">type ResponseController</a></li>
<li> <a href="#NewResponseController">func NewResponseController(rw ResponseWriter) *ResponseController</a>
</li>
<li> <a href="#ResponseController.EnableFullDuplex">func (c *ResponseController) EnableFullDuplex() error</a>
</li>
<li> <a href="#ResponseController.Flush">func (c *ResponseController) Flush() error</a>
</li>
<li> <a href="#ResponseController.Hijack">func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)</a>
</li>
<li> <a href="#ResponseController.SetReadDeadline">func (c *ResponseController) SetReadDeadline(deadline time.Time) error</a>
</li>
<li> <a href="#ResponseController.SetWriteDeadline">func (c *ResponseController) SetWriteDeadline(deadline time.Time) error</a>
</li>
<li><a href="#ResponseWriter">type ResponseWriter</a></li>
<li><a href="#RoundTripper">type RoundTripper</a></li>
<li> <a href="#NewFileTransport">func NewFileTransport(fs FileSystem) RoundTripper</a>
</li>
<li> <a href="#NewFileTransportFS">func NewFileTransportFS(fsys fs.FS) RoundTripper</a>
</li>
<li><a href="#SameSite">type SameSite</a></li>
<li><a href="#ServeMux">type ServeMux</a></li>
<li> <a href="#NewServeMux">func NewServeMux() *ServeMux</a>
</li>
<li> <a href="#ServeMux.Handle">func (mux *ServeMux) Handle(pattern string, handler Handler)</a>
</li>
<li> <a href="#ServeMux.HandleFunc">func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))</a>
</li>
<li> <a href="#ServeMux.Handler">func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)</a>
</li>
<li> <a href="#ServeMux.ServeHTTP">func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)</a>
</li>
<li><a href="#Server">type Server</a></li>
<li> <a href="#Server.Close">func (srv *Server) Close() error</a>
</li>
<li> <a href="#Server.ListenAndServe">func (srv *Server) ListenAndServe() error</a>
</li>
<li> <a href="#Server.ListenAndServeTLS">func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error</a>
</li>
<li> <a href="#Server.RegisterOnShutdown">func (srv *Server) RegisterOnShutdown(f func())</a>
</li>
<li> <a href="#Server.Serve">func (srv *Server) Serve(l net.Listener) error</a>
</li>
<li> <a href="#Server.ServeTLS">func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error</a>
</li>
<li> <a href="#Server.SetKeepAlivesEnabled">func (srv *Server) SetKeepAlivesEnabled(v bool)</a>
</li>
<li> <a href="#Server.Shutdown">func (srv *Server) Shutdown(ctx context.Context) error</a>
</li>
<li><a href="#Transport">type Transport</a></li>
<li> <a href="#Transport.CancelRequest">func (t *Transport) CancelRequest(req *Request)</a>
</li>
<li> <a href="#Transport.Clone">func (t *Transport) Clone() *Transport</a>
</li>
<li> <a href="#Transport.CloseIdleConnections">func (t *Transport) CloseIdleConnections()</a>
</li>
<li> <a href="#Transport.RegisterProtocol">func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)</a>
</li>
<li> <a href="#Transport.RoundTrip">func (t *Transport) RoundTrip(req *Request) (*Response, error)</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_FileServer">FileServer</a></dd> <dd><a class="exampleLink" href="#example_FileServer_dotFileHiding">FileServer (DotFileHiding)</a></dd> <dd><a class="exampleLink" href="#example_FileServer_stripPrefix">FileServer (StripPrefix)</a></dd> <dd><a class="exampleLink" href="#example_Get">Get</a></dd> <dd><a class="exampleLink" href="#example_Handle">Handle</a></dd> <dd><a class="exampleLink" href="#example_HandleFunc">HandleFunc</a></dd> <dd><a class="exampleLink" href="#example_Hijacker">Hijacker</a></dd> <dd><a class="exampleLink" href="#example_ListenAndServe">ListenAndServe</a></dd> <dd><a class="exampleLink" href="#example_ListenAndServeTLS">ListenAndServeTLS</a></dd> <dd><a class="exampleLink" href="#example_NotFoundHandler">NotFoundHandler</a></dd> <dd><a class="exampleLink" href="#example_ResponseWriter_trailers">ResponseWriter (Trailers)</a></dd> <dd><a class="exampleLink" href="#example_ServeMux_Handle">ServeMux.Handle</a></dd> <dd><a class="exampleLink" href="#example_Server_Shutdown">Server.Shutdown</a></dd> <dd><a class="exampleLink" href="#example_StripPrefix">StripPrefix</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>client.go</span> <span>clone.go</span> <span>cookie.go</span> <span>doc.go</span> <span>filetransport.go</span> <span>fs.go</span> <span>h2_bundle.go</span> <span>h2_error.go</span> <span>header.go</span> <span>http.go</span> <span>jar.go</span> <span>mapping.go</span> <span>method.go</span> <span>pattern.go</span> <span>request.go</span> <span>response.go</span> <span>responsecontroller.go</span> <span>roundtrip.go</span> <span>routing_index.go</span> <span>routing_tree.go</span> <span>servemux121.go</span> <span>server.go</span> <span>sniff.go</span> <span>socks_bundle.go</span> <span>status.go</span> <span>transfer.go</span> <span>transport.go</span> <span>transport_default_other.go</span>  </p>   <h2 id="pkg-constants">Constants</h2> <p>Common HTTP methods. </p>
<p>Unless otherwise noted, these are defined in RFC 7231 section 4.3. </p>
<pre data-language="go">const (
    MethodGet     = "GET"
    MethodHead    = "HEAD"
    MethodPost    = "POST"
    MethodPut     = "PUT"
    MethodPatch   = "PATCH" // RFC 5789
    MethodDelete  = "DELETE"
    MethodConnect = "CONNECT"
    MethodOptions = "OPTIONS"
    MethodTrace   = "TRACE"
)</pre> <p>HTTP status codes as registered with IANA. See: <a href="https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml">https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml</a> </p>
<pre data-language="go">const (
    StatusContinue           = 100 // RFC 9110, 15.2.1
    StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1
    StatusEarlyHints         = 103 // RFC 8297

    StatusOK                   = 200 // RFC 9110, 15.3.1
    StatusCreated              = 201 // RFC 9110, 15.3.2
    StatusAccepted             = 202 // RFC 9110, 15.3.3
    StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
    StatusNoContent            = 204 // RFC 9110, 15.3.5
    StatusResetContent         = 205 // RFC 9110, 15.3.6
    StatusPartialContent       = 206 // RFC 9110, 15.3.7
    StatusMultiStatus          = 207 // RFC 4918, 11.1
    StatusAlreadyReported      = 208 // RFC 5842, 7.1
    StatusIMUsed               = 226 // RFC 3229, 10.4.1

    StatusMultipleChoices  = 300 // RFC 9110, 15.4.1
    StatusMovedPermanently = 301 // RFC 9110, 15.4.2
    StatusFound            = 302 // RFC 9110, 15.4.3
    StatusSeeOther         = 303 // RFC 9110, 15.4.4
    StatusNotModified      = 304 // RFC 9110, 15.4.5
    StatusUseProxy         = 305 // RFC 9110, 15.4.6

    StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
    StatusPermanentRedirect = 308 // RFC 9110, 15.4.9

    StatusBadRequest                   = 400 // RFC 9110, 15.5.1
    StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
    StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
    StatusForbidden                    = 403 // RFC 9110, 15.5.4
    StatusNotFound                     = 404 // RFC 9110, 15.5.5
    StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
    StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
    StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
    StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
    StatusConflict                     = 409 // RFC 9110, 15.5.10
    StatusGone                         = 410 // RFC 9110, 15.5.11
    StatusLengthRequired               = 411 // RFC 9110, 15.5.12
    StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
    StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
    StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
    StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
    StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
    StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
    StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
    StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
    StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
    StatusLocked                       = 423 // RFC 4918, 11.3
    StatusFailedDependency             = 424 // RFC 4918, 11.4
    StatusTooEarly                     = 425 // RFC 8470, 5.2.
    StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
    StatusPreconditionRequired         = 428 // RFC 6585, 3
    StatusTooManyRequests              = 429 // RFC 6585, 4
    StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
    StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

    StatusInternalServerError           = 500 // RFC 9110, 15.6.1
    StatusNotImplemented                = 501 // RFC 9110, 15.6.2
    StatusBadGateway                    = 502 // RFC 9110, 15.6.3
    StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
    StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
    StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.6.6
    StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
    StatusInsufficientStorage           = 507 // RFC 4918, 11.5
    StatusLoopDetected                  = 508 // RFC 5842, 7.2
    StatusNotExtended                   = 510 // RFC 2774, 7
    StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)</pre> <p>DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting [Server.MaxHeaderBytes]. </p>
<pre data-language="go">const DefaultMaxHeaderBytes = 1 &lt;&lt; 20 // 1 MB
</pre> <p>DefaultMaxIdleConnsPerHost is the default value of <a href="#Transport">Transport</a>'s MaxIdleConnsPerHost. </p>
<pre data-language="go">const DefaultMaxIdleConnsPerHost = 2</pre> <p>TimeFormat is the time format to use when generating times in HTTP headers. It is like <span>time.RFC1123</span> but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format. </p>
<p>For parsing this time format, see <a href="#ParseTime">ParseTime</a>. </p>
<pre data-language="go">const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"</pre> <p>TrailerPrefix is a magic prefix for [ResponseWriter.Header] map keys that, if present, signals that the map entry is actually for the response trailers, and not the response headers. The prefix is stripped after the ServeHTTP call finishes and the values are sent in the trailers. </p>
<p>This mechanism is intended only for trailers that are not known prior to the headers being written. If the set of trailers is fixed or known before the header is written, the normal Go trailers mechanism is preferred: </p>
<pre data-language="go">https://pkg.go.dev/net/http#ResponseWriter
https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
</pre> <pre data-language="go">const TrailerPrefix = "Trailer:"</pre> <h2 id="pkg-variables">Variables</h2> <pre data-language="go">var (
    // ErrNotSupported indicates that a feature is not supported.
    //
    // It is returned by ResponseController methods to indicate that
    // the handler does not support the method, and by the Push method
    // of Pusher implementations to indicate that HTTP/2 Push support
    // is not available.
    ErrNotSupported = &amp;ProtocolError{"feature not supported"}

    // Deprecated: ErrUnexpectedTrailer is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrUnexpectedTrailer = &amp;ProtocolError{"trailer header without chunked transfer encoding"}

    // ErrMissingBoundary is returned by Request.MultipartReader when the
    // request's Content-Type does not include a "boundary" parameter.
    ErrMissingBoundary = &amp;ProtocolError{"no multipart boundary param in Content-Type"}

    // ErrNotMultipart is returned by Request.MultipartReader when the
    // request's Content-Type is not multipart/form-data.
    ErrNotMultipart = &amp;ProtocolError{"request Content-Type isn't multipart/form-data"}

    // Deprecated: ErrHeaderTooLong is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrHeaderTooLong = &amp;ProtocolError{"header too long"}

    // Deprecated: ErrShortBody is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrShortBody = &amp;ProtocolError{"entity body too short"}

    // Deprecated: ErrMissingContentLength is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrMissingContentLength = &amp;ProtocolError{"missing ContentLength in HEAD response"}
)</pre> <p>Errors used by the HTTP server. </p>
<pre data-language="go">var (
    // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
    // when the HTTP method or response code does not permit a
    // body.
    ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")

    // ErrHijacked is returned by ResponseWriter.Write calls when
    // the underlying connection has been hijacked using the
    // Hijacker interface. A zero-byte write on a hijacked
    // connection will return ErrHijacked without any other side
    // effects.
    ErrHijacked = errors.New("http: connection has been hijacked")

    // ErrContentLength is returned by ResponseWriter.Write calls
    // when a Handler set a Content-Length response header with a
    // declared size and then attempted to write more bytes than
    // declared.
    ErrContentLength = errors.New("http: wrote more than the declared Content-Length")

    // Deprecated: ErrWriteAfterFlush is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrWriteAfterFlush = errors.New("unused")
)</pre> <pre data-language="go">var (
    // ServerContextKey is a context key. It can be used in HTTP
    // handlers with Context.Value to access the server that
    // started the handler. The associated value will be of
    // type *Server.
    ServerContextKey = &amp;contextKey{"http-server"}

    // LocalAddrContextKey is a context key. It can be used in
    // HTTP handlers with Context.Value to access the local
    // address the connection arrived on.
    // The associated value will be of type net.Addr.
    LocalAddrContextKey = &amp;contextKey{"local-addr"}
)</pre> <p>DefaultClient is the default <a href="#Client">Client</a> and is used by <a href="#Get">Get</a>, <a href="#Head">Head</a>, and <a href="#Post">Post</a>. </p>
<pre data-language="go">var DefaultClient = &amp;Client{}</pre> <p>DefaultServeMux is the default <a href="#ServeMux">ServeMux</a> used by <a href="#Serve">Serve</a>. </p>
<pre data-language="go">var DefaultServeMux = &amp;defaultServeMux</pre> <p>ErrAbortHandler is a sentinel panic value to abort a handler. While any panic from ServeHTTP aborts the response to the client, panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log. </p>
<pre data-language="go">var ErrAbortHandler = errors.New("net/http: abort Handler")</pre> <p>ErrBodyReadAfterClose is returned when reading a <a href="#Request">Request</a> or <a href="#Response">Response</a> Body after the body has been closed. This typically happens when the body is read after an HTTP <a href="#Handler">Handler</a> calls WriteHeader or Write on its <a href="#ResponseWriter">ResponseWriter</a>. </p>
<pre data-language="go">var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")</pre> <p>ErrHandlerTimeout is returned on <a href="#ResponseWriter">ResponseWriter</a> Write calls in handlers which have timed out. </p>
<pre data-language="go">var ErrHandlerTimeout = errors.New("http: Handler timeout")</pre> <p>ErrLineTooLong is returned when reading request or response bodies with malformed chunked encoding. </p>
<pre data-language="go">var ErrLineTooLong = internal.ErrLineTooLong</pre> <p>ErrMissingFile is returned by FormFile when the provided file field name is either not present in the request or not a file field. </p>
<pre data-language="go">var ErrMissingFile = errors.New("http: no such file")</pre> <p>ErrNoCookie is returned by Request's Cookie method when a cookie is not found. </p>
<pre data-language="go">var ErrNoCookie = errors.New("http: named cookie not present")</pre> <p>ErrNoLocation is returned by the <a href="#Response.Location">Response.Location</a> method when no Location header is present. </p>
<pre data-language="go">var ErrNoLocation = errors.New("http: no Location header in response")</pre> <p>ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client. </p>
<pre data-language="go">var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client")</pre> <p>ErrServerClosed is returned by the <a href="#Server.Serve">Server.Serve</a>, <a href="#ServeTLS">ServeTLS</a>, <a href="#ListenAndServe">ListenAndServe</a>, and <a href="#ListenAndServeTLS">ListenAndServeTLS</a> methods after a call to <a href="#Server.Shutdown">Server.Shutdown</a> or <a href="#Server.Close">Server.Close</a>. </p>
<pre data-language="go">var ErrServerClosed = errors.New("http: Server closed")</pre> <p>ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol. </p>
<pre data-language="go">var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")</pre> <p>ErrUseLastResponse can be returned by Client.CheckRedirect hooks to control how redirects are processed. If returned, the next request is not sent and the most recent response is returned with its body unclosed. </p>
<pre data-language="go">var ErrUseLastResponse = errors.New("net/http: use last response")</pre> <p>NoBody is an <span>io.ReadCloser</span> with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set [Request.Body] to nil. </p>
<pre data-language="go">var NoBody = noBody{}</pre> <h2 id="CanonicalHeaderKey">func <span>CanonicalHeaderKey</span>  </h2> <pre data-language="go">func CanonicalHeaderKey(s string) string</pre> <p>CanonicalHeaderKey returns the canonical format of the header key s. The canonicalization converts the first letter and any letter following a hyphen to upper case; the rest are converted to lowercase. For example, the canonical key for "accept-encoding" is "Accept-Encoding". If s contains a space or invalid header field bytes, it is returned without modifications. </p>
<h2 id="DetectContentType">func <span>DetectContentType</span>  </h2> <pre data-language="go">func DetectContentType(data []byte) string</pre> <p>DetectContentType implements the algorithm described at <a href="https://mimesniff.spec.whatwg.org/">https://mimesniff.spec.whatwg.org/</a> to determine the Content-Type of the given data. It considers at most the first 512 bytes of data. DetectContentType always returns a valid MIME type: if it cannot determine a more specific one, it returns "application/octet-stream". </p>
<h2 id="Error">func <span>Error</span>  </h2> <pre data-language="go">func Error(w ResponseWriter, error string, code int)</pre> <p>Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text. </p>
<h2 id="Handle">func <span>Handle</span>  </h2> <pre data-language="go">func Handle(pattern string, handler Handler)</pre> <p>Handle registers the handler for the given pattern in <a href="#DefaultServeMux">DefaultServeMux</a>. The documentation for <a href="#ServeMux">ServeMux</a> explains how patterns are matched. </p>   <h4 id="example_Handle"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package http_test

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

type countHandler struct {
    mu sync.Mutex // guards n
    n  int
}

func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    h.mu.Lock()
    defer h.mu.Unlock()
    h.n++
    fmt.Fprintf(w, "count is %d\n", h.n)
}

func ExampleHandle() {
    http.Handle("/count", new(countHandler))
    log.Fatal(http.ListenAndServe(":8080", nil))
}
</pre>   <h2 id="HandleFunc">func <span>HandleFunc</span>  </h2> <pre data-language="go">func HandleFunc(pattern string, handler func(ResponseWriter, *Request))</pre> <p>HandleFunc registers the handler function for the given pattern in <a href="#DefaultServeMux">DefaultServeMux</a>. The documentation for <a href="#ServeMux">ServeMux</a> explains how patterns are matched. </p>   <h4 id="example_HandleFunc"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
h1 := func(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello from a HandleFunc #1!\n")
}
h2 := func(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello from a HandleFunc #2!\n")
}

http.HandleFunc("/", h1)
http.HandleFunc("/endpoint", h2)

log.Fatal(http.ListenAndServe(":8080", nil))
</pre>   <h2 id="ListenAndServe">func <span>ListenAndServe</span>  </h2> <pre data-language="go">func ListenAndServe(addr string, handler Handler) error</pre> <p>ListenAndServe listens on the TCP network address addr and then calls <a href="#Serve">Serve</a> with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives. </p>
<p>The handler is typically nil, in which case <a href="#DefaultServeMux">DefaultServeMux</a> is used. </p>
<p>ListenAndServe always returns a non-nil error. </p>   <h4 id="example_ListenAndServe"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// Hello world, the web server

helloHandler := func(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "Hello, world!\n")
}

http.HandleFunc("/hello", helloHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
</pre>   <h2 id="ListenAndServeTLS">func <span>ListenAndServeTLS</span>  </h2> <pre data-language="go">func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error</pre> <p>ListenAndServeTLS acts identically to <a href="#ListenAndServe">ListenAndServe</a>, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate. </p>   <h4 id="example_ListenAndServeTLS"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "Hello, TLS!\n")
})

// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
log.Fatal(err)
</pre>   <h2 id="MaxBytesReader">func <span>MaxBytesReader</span>  </h2> <pre data-language="go">func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser</pre> <p>MaxBytesReader is similar to <span>io.LimitReader</span> but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-nil error of type <a href="#MaxBytesError">*MaxBytesError</a> for a Read beyond the limit, and closes the underlying reader when its Close method is called. </p>
<p>MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources. If possible, it tells the <a href="#ResponseWriter">ResponseWriter</a> to close the connection after the limit has been reached. </p>
<h2 id="NotFound">func <span>NotFound</span>  </h2> <pre data-language="go">func NotFound(w ResponseWriter, r *Request)</pre> <p>NotFound replies to the request with an HTTP 404 not found error. </p>
<h2 id="ParseHTTPVersion">func <span>ParseHTTPVersion</span>  </h2> <pre data-language="go">func ParseHTTPVersion(vers string) (major, minor int, ok bool)</pre> <p>ParseHTTPVersion parses an HTTP version string according to RFC 7230, section 2.6. "HTTP/1.0" returns (1, 0, true). Note that strings without a minor version, such as "HTTP/2", are not valid. </p>
<h2 id="ParseTime">func <span>ParseTime</span>  <span title="Added in Go 1.1">1.1</span> </h2> <pre data-language="go">func ParseTime(text string) (t time.Time, err error)</pre> <p>ParseTime parses a time header (such as the Date: header), trying each of the three formats allowed by HTTP/1.1: <a href="#TimeFormat">TimeFormat</a>, <span>time.RFC850</span>, and <span>time.ANSIC</span>. </p>
<h2 id="ProxyFromEnvironment">func <span>ProxyFromEnvironment</span>  </h2> <pre data-language="go">func ProxyFromEnvironment(req *Request) (*url.URL, error)</pre> <p>ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). Requests use the proxy from the environment variable matching their scheme, unless excluded by NO_PROXY. </p>
<p>The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. The schemes "http", "https", and "socks5" are supported. An error is returned if the value is a different form. </p>
<p>A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY. </p>
<p>As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned. </p>
<h2 id="ProxyURL">func <span>ProxyURL</span>  </h2> <pre data-language="go">func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)</pre> <p>ProxyURL returns a proxy function (for use in a <a href="#Transport">Transport</a>) that always returns the same URL. </p>
<h2 id="Redirect">func <span>Redirect</span>  </h2> <pre data-language="go">func Redirect(w ResponseWriter, r *Request, url string, code int)</pre> <p>Redirect replies to the request with a redirect to url, which may be a path relative to the request path. </p>
<p>The provided code should be in the 3xx range and is usually <a href="#StatusMovedPermanently">StatusMovedPermanently</a>, <a href="#StatusFound">StatusFound</a> or <a href="#StatusSeeOther">StatusSeeOther</a>. </p>
<p>If the Content-Type header has not been set, <a href="#Redirect">Redirect</a> sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior. </p>
<h2 id="Serve">func <span>Serve</span>  </h2> <pre data-language="go">func Serve(l net.Listener, handler Handler) error</pre> <p>Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them. </p>
<p>The handler is typically nil, in which case <a href="#DefaultServeMux">DefaultServeMux</a> is used. </p>
<p>HTTP/2 support is only enabled if the Listener returns <span>*tls.Conn</span> connections and they were configured with "h2" in the TLS Config.NextProtos. </p>
<p>Serve always returns a non-nil error. </p>
<h2 id="ServeContent">func <span>ServeContent</span>  </h2> <pre data-language="go">func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)</pre> <p>ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over <span>io.Copy</span> is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests. </p>
<p>If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to <a href="#DetectContentType">DetectContentType</a>. The name is otherwise unused; in particular it can be empty and is never sent in the response. </p>
<p>If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all. </p>
<p>The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size. </p>
<p>If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range. </p>
<p>Note that <span>*os.File</span> implements the <span>io.ReadSeeker</span> interface. </p>
<h2 id="ServeFile">func <span>ServeFile</span>  </h2> <pre data-language="go">func ServeFile(w ResponseWriter, r *Request, name string)</pre> <p>ServeFile replies to the request with the contents of the named file or directory. </p>
<p>If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile. </p>
<p>As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use <span>filepath.Join</span> on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument. </p>
<p>As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use <a href="#ServeContent">ServeContent</a>. </p>
<p>Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used. </p>
<h2 id="ServeFileFS">func <span>ServeFileFS</span>  <span title="Added in Go 1.22">1.22</span> </h2> <pre data-language="go">func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)</pre> <p>ServeFileFS replies to the request with the contents of the named file or directory from the file system fsys. </p>
<p>If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling <a href="#ServeFile">ServeFile</a>. </p>
<p>As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use <span>filepath.Join</span> on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument. </p>
<p>As another special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent. </p>
<p>Outside of those two special cases, ServeFile does not use r.URL.Path for selecting the file or directory to serve; only the file or directory provided in the name argument is used. </p>
<h2 id="ServeTLS">func <span>ServeTLS</span>  <span title="Added in Go 1.9">1.9</span> </h2> <pre data-language="go">func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error</pre> <p>ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them. </p>
<p>The handler is typically nil, in which case <a href="#DefaultServeMux">DefaultServeMux</a> is used. </p>
<p>Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate. </p>
<p>ServeTLS always returns a non-nil error. </p>
<h2 id="SetCookie">func <span>SetCookie</span>  </h2> <pre data-language="go">func SetCookie(w ResponseWriter, cookie *Cookie)</pre> <p>SetCookie adds a Set-Cookie header to the provided <a href="#ResponseWriter">ResponseWriter</a>'s headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped. </p>
<h2 id="StatusText">func <span>StatusText</span>  </h2> <pre data-language="go">func StatusText(code int) string</pre> <p>StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown. </p>
<h2 id="Client">type <span>Client</span>  </h2> <p>A Client is an HTTP client. Its zero value (<a href="#DefaultClient">DefaultClient</a>) is a usable client that uses <a href="#DefaultTransport">DefaultTransport</a>. </p>
<p>The [Client.Transport] typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines. </p>
<p>A Client is higher-level than a <a href="#RoundTripper">RoundTripper</a> (such as <a href="#Transport">Transport</a>) and additionally handles HTTP details such as cookies and redirects. </p>
<p>When following redirects, the Client will forward all headers set on the initial <a href="#Request">Request</a> except: </p>
<ul> <li>when forwarding sensitive headers like "Authorization", "WWW-Authenticate", and "Cookie" to untrusted targets. These headers will be ignored when following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but a redirect to "bar.com" will not. </li>
<li>when forwarding the "Cookie" header with a non-nil cookie Jar. Since each redirect may mutate the state of the cookie jar, a redirect may possibly alter a cookie set in the initial request. When forwarding the "Cookie" header, any mutated cookies will be omitted, with the expectation that the Jar will insert those mutated cookies with the updated values (assuming the origin matches). If Jar is nil, the initial cookies are forwarded without change. </li>
</ul> <pre data-language="go">type Client struct {
    // Transport specifies the mechanism by which individual
    // HTTP requests are made.
    // If nil, DefaultTransport is used.
    Transport RoundTripper

    // CheckRedirect specifies the policy for handling redirects.
    // If CheckRedirect is not nil, the client calls it before
    // following an HTTP redirect. The arguments req and via are
    // the upcoming request and the requests made already, oldest
    // first. If CheckRedirect returns an error, the Client's Get
    // method returns both the previous Response (with its Body
    // closed) and CheckRedirect's error (wrapped in a url.Error)
    // instead of issuing the Request req.
    // As a special case, if CheckRedirect returns ErrUseLastResponse,
    // then the most recent response is returned with its body
    // unclosed, along with a nil error.
    //
    // If CheckRedirect is nil, the Client uses its default policy,
    // which is to stop after 10 consecutive requests.
    CheckRedirect func(req *Request, via []*Request) error

    // Jar specifies the cookie jar.
    //
    // The Jar is used to insert relevant cookies into every
    // outbound Request and is updated with the cookie values
    // of every inbound Response. The Jar is consulted for every
    // redirect that the Client follows.
    //
    // If Jar is nil, cookies are only sent if they are explicitly
    // set on the Request.
    Jar CookieJar

    // Timeout specifies a time limit for requests made by this
    // Client. The timeout includes connection time, any
    // redirects, and reading the response body. The timer remains
    // running after Get, Head, Post, or Do return and will
    // interrupt reading of the Response.Body.
    //
    // A Timeout of zero means no timeout.
    //
    // The Client cancels requests to the underlying Transport
    // as if the Request's Context ended.
    //
    // For compatibility, the Client will also use the deprecated
    // CancelRequest method on Transport if found. New
    // RoundTripper implementations should use the Request's Context
    // for cancellation instead of implementing CancelRequest.
    Timeout time.Duration // Go 1.3
}
</pre> <h3 id="Client.CloseIdleConnections">func (*Client) <span>CloseIdleConnections</span>  <span title="Added in Go 1.12">1.12</span> </h3> <pre data-language="go">func (c *Client) CloseIdleConnections()</pre> <p>CloseIdleConnections closes any connections on its <a href="#Transport">Transport</a> which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use. </p>
<p>If [Client.Transport] does not have a <a href="#Client.CloseIdleConnections">Client.CloseIdleConnections</a> method then this method does nothing. </p>
<h3 id="Client.Do">func (*Client) <span>Do</span>  </h3> <pre data-language="go">func (c *Client) Do(req *Request) (*Response, error)</pre> <p>Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. </p>
<p>An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error. </p>
<p>If the returned error is nil, the <a href="#Response">Response</a> will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the <a href="#Client">Client</a>'s underlying <a href="#RoundTripper">RoundTripper</a> (typically <a href="#Transport">Transport</a>) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request. </p>
<p>The request Body, if non-nil, will be closed by the underlying Transport, even on errors. The Body may be closed asynchronously after Do returns. </p>
<p>On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned [Response.Body] is already closed. </p>
<p>Generally <a href="#Get">Get</a>, <a href="#Post">Post</a>, or <a href="#PostForm">PostForm</a> will be used instead of Do. </p>
<p>If the server replies with a redirect, the Client first uses the CheckRedirect function to determine whether the redirect should be followed. If permitted, a 301, 302, or 303 redirect causes subsequent requests to use HTTP method GET (or HEAD if the original request was HEAD), with no body. A 307 or 308 redirect preserves the original HTTP method and body, provided that the [Request.GetBody] function is defined. The <a href="#NewRequest">NewRequest</a> function automatically sets GetBody for common standard library body types. </p>
<p>Any returned error will be of type <span>*url.Error</span>. The url.Error value's Timeout method will report true if the request timed out. </p>
<h3 id="Client.Get">func (*Client) <span>Get</span>  </h3> <pre data-language="go">func (c *Client) Get(url string) (resp *Response, err error)</pre> <p>Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the [Client.CheckRedirect] function: </p>
<pre data-language="go">301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
</pre> <p>An error is returned if the [Client.CheckRedirect] function fails or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type <span>*url.Error</span>. The url.Error value's Timeout method will report true if the request timed out. </p>
<p>When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. </p>
<p>To make a request with custom headers, use <a href="#NewRequest">NewRequest</a> and <a href="#Client.Do">Client.Do</a>. </p>
<p>To make a request with a specified context.Context, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and Client.Do. </p>
<h3 id="Client.Head">func (*Client) <span>Head</span>  </h3> <pre data-language="go">func (c *Client) Head(url string) (resp *Response, err error)</pre> <p>Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the [Client.CheckRedirect] function: </p>
<pre data-language="go">301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
</pre> <p>To make a request with a specified <span>context.Context</span>, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and <a href="#Client.Do">Client.Do</a>. </p>
<h3 id="Client.Post">func (*Client) <span>Post</span>  </h3> <pre data-language="go">func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)</pre> <p>Post issues a POST to the specified URL. </p>
<p>Caller should close resp.Body when done reading from it. </p>
<p>If the provided body is an <span>io.Closer</span>, it is closed after the request. </p>
<p>To set custom headers, use <a href="#NewRequest">NewRequest</a> and <a href="#Client.Do">Client.Do</a>. </p>
<p>To make a request with a specified context.Context, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and <a href="#Client.Do">Client.Do</a>. </p>
<p>See the Client.Do method documentation for details on how redirects are handled. </p>
<h3 id="Client.PostForm">func (*Client) <span>PostForm</span>  </h3> <pre data-language="go">func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)</pre> <p>PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body. </p>
<p>The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use <a href="#NewRequest">NewRequest</a> and <a href="#Client.Do">Client.Do</a>. </p>
<p>When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. </p>
<p>See the Client.Do method documentation for details on how redirects are handled. </p>
<p>To make a request with a specified context.Context, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and Client.Do. </p>
<h2 id="CloseNotifier">type <span>CloseNotifier</span>  <span title="Added in Go 1.1">1.1</span> </h2> <p>The CloseNotifier interface is implemented by ResponseWriters which allow detecting when the underlying connection has gone away. </p>
<p>This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. </p>
<p>Deprecated: the CloseNotifier interface predates Go's context package. New code should use <a href="#Request.Context">Request.Context</a> instead. </p>
<pre data-language="go">type CloseNotifier interface {
    // CloseNotify returns a channel that receives at most a
    // single value (true) when the client connection has gone
    // away.
    //
    // CloseNotify may wait to notify until Request.Body has been
    // fully read.
    //
    // After the Handler has returned, there is no guarantee
    // that the channel receives a value.
    //
    // If the protocol is HTTP/1.1 and CloseNotify is called while
    // processing an idempotent request (such a GET) while
    // HTTP/1.1 pipelining is in use, the arrival of a subsequent
    // pipelined request may cause a value to be sent on the
    // returned channel. In practice HTTP/1.1 pipelining is not
    // enabled in browsers and not seen often in the wild. If this
    // is a problem, use HTTP/2 or only use CloseNotify on methods
    // such as POST.
    CloseNotify() &lt;-chan bool
}</pre> <h2 id="ConnState">type <span>ConnState</span>  <span title="Added in Go 1.3">1.3</span> </h2> <p>A ConnState represents the state of a client connection to a server. It's used by the optional [Server.ConnState] hook. </p>
<pre data-language="go">type ConnState int</pre> <pre data-language="go">const (
    // StateNew represents a new connection that is expected to
    // send a request immediately. Connections begin at this
    // state and then transition to either StateActive or
    // StateClosed.
    StateNew ConnState = iota

    // StateActive represents a connection that has read 1 or more
    // bytes of a request. The Server.ConnState hook for
    // StateActive fires before the request has entered a handler
    // and doesn't fire again until the request has been
    // handled. After the request is handled, the state
    // transitions to StateClosed, StateHijacked, or StateIdle.
    // For HTTP/2, StateActive fires on the transition from zero
    // to one active request, and only transitions away once all
    // active requests are complete. That means that ConnState
    // cannot be used to do per-request work; ConnState only notes
    // the overall state of the connection.
    StateActive

    // StateIdle represents a connection that has finished
    // handling a request and is in the keep-alive state, waiting
    // for a new request. Connections transition from StateIdle
    // to either StateActive or StateClosed.
    StateIdle

    // StateHijacked represents a hijacked connection.
    // This is a terminal state. It does not transition to StateClosed.
    StateHijacked

    // StateClosed represents a closed connection.
    // This is a terminal state. Hijacked connections do not
    // transition to StateClosed.
    StateClosed
)</pre> <h3 id="ConnState.String">func (ConnState) <span>String</span>  <span title="Added in Go 1.3">1.3</span> </h3> <pre data-language="go">func (c ConnState) String() string</pre> <h2 id="Cookie">type <span>Cookie</span>  </h2> <p>A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request. </p>
<p>See <a href="https://tools.ietf.org/html/rfc6265">https://tools.ietf.org/html/rfc6265</a> for details. </p>
<pre data-language="go">type Cookie struct {
    Name  string
    Value string

    Path       string    // optional
    Domain     string    // optional
    Expires    time.Time // optional
    RawExpires string    // for reading cookies only

    // MaxAge=0 means no 'Max-Age' attribute specified.
    // MaxAge&lt;0 means delete cookie now, equivalently 'Max-Age: 0'
    // MaxAge&gt;0 means Max-Age attribute present and given in seconds
    MaxAge   int
    Secure   bool
    HttpOnly bool
    SameSite SameSite // Go 1.11
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}
</pre> <h3 id="Cookie.String">func (*Cookie) <span>String</span>  </h3> <pre data-language="go">func (c *Cookie) String() string</pre> <p>String returns the serialization of the cookie for use in a <a href="#Cookie">Cookie</a> header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set). If c is nil or c.Name is invalid, the empty string is returned. </p>
<h3 id="Cookie.Valid">func (*Cookie) <span>Valid</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *Cookie) Valid() error</pre> <p>Valid reports whether the cookie is valid. </p>
<h2 id="CookieJar">type <span>CookieJar</span>  </h2> <p>A CookieJar manages storage and use of cookies in HTTP requests. </p>
<p>Implementations of CookieJar must be safe for concurrent use by multiple goroutines. </p>
<p>The net/http/cookiejar package provides a CookieJar implementation. </p>
<pre data-language="go">type CookieJar interface {
    // SetCookies handles the receipt of the cookies in a reply for the
    // given URL.  It may or may not choose to save the cookies, depending
    // on the jar's policy and implementation.
    SetCookies(u *url.URL, cookies []*Cookie)

    // Cookies returns the cookies to send in a request for the given URL.
    // It is up to the implementation to honor the standard cookie use
    // restrictions such as in RFC 6265.
    Cookies(u *url.URL) []*Cookie
}</pre> <h2 id="Dir">type <span>Dir</span>  </h2> <p>A Dir implements <a href="#FileSystem">FileSystem</a> using the native file system restricted to a specific directory tree. </p>
<p>While the [FileSystem.Open] method takes '/'-separated paths, a Dir's string value is a filename on the native file system, not a URL, so it is separated by <span>filepath.Separator</span>, which isn't necessarily '/'. </p>
<p>Note that Dir could expose sensitive files and directories. Dir will follow symlinks pointing out of the directory tree, which can be especially dangerous if serving from a directory in which users are able to create arbitrary symlinks. Dir will also allow access to files and directories starting with a period, which could expose sensitive directories like .git or sensitive files like .htpasswd. To exclude files with a leading period, remove the files/directories from the server or create a custom FileSystem implementation. </p>
<p>An empty Dir is treated as ".". </p>
<pre data-language="go">type Dir string</pre> <h3 id="Dir.Open">func (Dir) <span>Open</span>  </h3> <pre data-language="go">func (d Dir) Open(name string) (File, error)</pre> <p>Open implements <a href="#FileSystem">FileSystem</a> using <span>os.Open</span>, opening files for reading rooted and relative to the directory d. </p>
<h2 id="File">type <span>File</span>  </h2> <p>A File is returned by a <a href="#FileSystem">FileSystem</a>'s Open method and can be served by the <a href="#FileServer">FileServer</a> implementation. </p>
<p>The methods should behave the same as those on an <span>*os.File</span>. </p>
<pre data-language="go">type File interface {
    io.Closer
    io.Reader
    io.Seeker
    Readdir(count int) ([]fs.FileInfo, error)
    Stat() (fs.FileInfo, error)
}</pre> <h2 id="FileSystem">type <span>FileSystem</span>  </h2> <p>A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash ('/', U+002F) characters, regardless of host operating system convention. See the <a href="#FileServer">FileServer</a> function to convert a FileSystem to a <a href="#Handler">Handler</a>. </p>
<p>This interface predates the <span>fs.FS</span> interface, which can be used instead: the <a href="#FS">FS</a> adapter function converts an fs.FS to a FileSystem. </p>
<pre data-language="go">type FileSystem interface {
    Open(name string) (File, error)
}</pre> <h3 id="FS">func <span>FS</span>  <span title="Added in Go 1.16">1.16</span> </h3> <pre data-language="go">func FS(fsys fs.FS) FileSystem</pre> <p>FS converts fsys to a <a href="#FileSystem">FileSystem</a> implementation, for use with <a href="#FileServer">FileServer</a> and <a href="#NewFileTransport">NewFileTransport</a>. The files provided by fsys must implement <span>io.Seeker</span>. </p>
<h2 id="Flusher">type <span>Flusher</span>  </h2> <p>The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client. </p>
<p>The default HTTP/1.x and HTTP/2 <a href="#ResponseWriter">ResponseWriter</a> implementations support <a href="#Flusher">Flusher</a>, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime. </p>
<p>Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes. </p>
<pre data-language="go">type Flusher interface {
    // Flush sends any buffered data to the client.
    Flush()
}</pre> <h2 id="Handler">type <span>Handler</span>  </h2> <p>A Handler responds to an HTTP request. </p>
<p>[Handler.ServeHTTP] should write reply headers and data to the <a href="#ResponseWriter">ResponseWriter</a> and then return. Returning signals that the request is finished; it is not valid to use the <a href="#ResponseWriter">ResponseWriter</a> or read from the [Request.Body] after or concurrently with the completion of the ServeHTTP call. </p>
<p>Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the [Request.Body] after writing to the <a href="#ResponseWriter">ResponseWriter</a>. Cautious handlers should read the [Request.Body] first, and then reply. </p>
<p>Except for reading the body, handlers should not modify the provided Request. </p>
<p>If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value <a href="#ErrAbortHandler">ErrAbortHandler</a>. </p>
<pre data-language="go">type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}</pre> <h3 id="AllowQuerySemicolons">func <span>AllowQuerySemicolons</span>  <span title="Added in Go 1.17">1.17</span> </h3> <pre data-language="go">func AllowQuerySemicolons(h Handler) Handler</pre> <p>AllowQuerySemicolons returns a handler that serves requests by converting any unescaped semicolons in the URL query to ampersands, and invoking the handler h. </p>
<p>This restores the pre-Go 1.17 behavior of splitting query parameters on both semicolons and ampersands. (See golang.org/issue/25192). Note that this behavior doesn't match that of many proxies, and the mismatch can lead to security issues. </p>
<p>AllowQuerySemicolons should be invoked before <a href="#Request.ParseForm">Request.ParseForm</a> is called. </p>
<h3 id="FileServer">func <span>FileServer</span>  </h3> <pre data-language="go">func FileServer(root FileSystem) Handler</pre> <p>FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root. </p>
<p>As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html". </p>
<p>To use the operating system's file system implementation, use <a href="#Dir">http.Dir</a>: </p>
<pre data-language="go">http.Handle("/", http.FileServer(http.Dir("/tmp")))
</pre> <p>To use an <span>fs.FS</span> implementation, use <a href="#FileServerFS">http.FileServerFS</a> instead. </p>   <h4 id="example_FileServer"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// Simple static webserver:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
</pre>      <h4 id="example_FileServer_dotFileHiding"> <span class="text">Example (DotFileHiding)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package http_test

import (
    "io/fs"
    "log"
    "net/http"
    "strings"
)

// containsDotFile reports whether name contains a path element starting with a period.
// The name is assumed to be a delimited by forward slashes, as guaranteed
// by the http.FileSystem interface.
func containsDotFile(name string) bool {
    parts := strings.Split(name, "/")
    for _, part := range parts {
        if strings.HasPrefix(part, ".") {
            return true
        }
    }
    return false
}

// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
// It is used to wrap the Readdir method of http.File so that we can
// remove files and directories that start with a period from its output.
type dotFileHidingFile struct {
    http.File
}

// Readdir is a wrapper around the Readdir method of the embedded File
// that filters out all files that start with a period in their name.
func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
    files, err := f.File.Readdir(n)
    for _, file := range files { // Filters out the dot files
        if !strings.HasPrefix(file.Name(), ".") {
            fis = append(fis, file)
        }
    }
    return
}

// dotFileHidingFileSystem is an http.FileSystem that hides
// hidden "dot files" from being served.
type dotFileHidingFileSystem struct {
    http.FileSystem
}

// Open is a wrapper around the Open method of the embedded FileSystem
// that serves a 403 permission error when name has a file or directory
// with whose name starts with a period in its path.
func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
    if containsDotFile(name) { // If dot file, return 403 response
        return nil, fs.ErrPermission
    }

    file, err := fsys.FileSystem.Open(name)
    if err != nil {
        return nil, err
    }
    return dotFileHidingFile{file}, err
}

func ExampleFileServer_dotFileHiding() {
    fsys := dotFileHidingFileSystem{http.Dir(".")}
    http.Handle("/", http.FileServer(fsys))
    log.Fatal(http.ListenAndServe(":8080", nil))
}
</pre>      <h4 id="example_FileServer_stripPrefix"> <span class="text">Example (StripPrefix)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
</pre>   <h3 id="FileServerFS">func <span>FileServerFS</span>  <span title="Added in Go 1.22">1.22</span> </h3> <pre data-language="go">func FileServerFS(root fs.FS) Handler</pre> <p>FileServerFS returns a handler that serves HTTP requests with the contents of the file system fsys. </p>
<p>As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html". </p>
<pre data-language="go">http.Handle("/", http.FileServerFS(fsys))
</pre> <h3 id="MaxBytesHandler">func <span>MaxBytesHandler</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func MaxBytesHandler(h Handler, n int64) Handler</pre> <p>MaxBytesHandler returns a <a href="#Handler">Handler</a> that runs h with its <a href="#ResponseWriter">ResponseWriter</a> and [Request.Body] wrapped by a MaxBytesReader. </p>
<h3 id="NotFoundHandler">func <span>NotFoundHandler</span>  </h3> <pre data-language="go">func NotFoundHandler() Handler</pre> <p>NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply. </p>   <h4 id="example_NotFoundHandler"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
mux := http.NewServeMux()

// Create sample handler to returns 404
mux.Handle("/resources", http.NotFoundHandler())

// Create sample handler that returns 200
mux.Handle("/resources/people/", newPeopleHandler())

log.Fatal(http.ListenAndServe(":8080", mux))
</pre>   <h3 id="RedirectHandler">func <span>RedirectHandler</span>  </h3> <pre data-language="go">func RedirectHandler(url string, code int) Handler</pre> <p>RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code. </p>
<p>The provided code should be in the 3xx range and is usually <a href="#StatusMovedPermanently">StatusMovedPermanently</a>, <a href="#StatusFound">StatusFound</a> or <a href="#StatusSeeOther">StatusSeeOther</a>. </p>
<h3 id="StripPrefix">func <span>StripPrefix</span>  </h3> <pre data-language="go">func StripPrefix(prefix string, h Handler) Handler</pre> <p>StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error. The prefix must match exactly: if the prefix in the request contains escaped characters the reply is also an HTTP 404 not found error. </p>   <h4 id="example_StripPrefix"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
</pre>   <h3 id="TimeoutHandler">func <span>TimeoutHandler</span>  </h3> <pre data-language="go">func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler</pre> <p>TimeoutHandler returns a <a href="#Handler">Handler</a> that runs h with the given time limit. </p>
<p>The new Handler calls h.ServeHTTP to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its <a href="#ResponseWriter">ResponseWriter</a> will return <a href="#ErrHandlerTimeout">ErrHandlerTimeout</a>. </p>
<p>TimeoutHandler supports the <a href="#Pusher">Pusher</a> interface but does not support the <a href="#Hijacker">Hijacker</a> or <a href="#Flusher">Flusher</a> interfaces. </p>
<h2 id="HandlerFunc">type <span>HandlerFunc</span>  </h2> <p>The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a <a href="#Handler">Handler</a> that calls f. </p>
<pre data-language="go">type HandlerFunc func(ResponseWriter, *Request)</pre> <h3 id="HandlerFunc.ServeHTTP">func (HandlerFunc) <span>ServeHTTP</span>  </h3> <pre data-language="go">func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)</pre> <p>ServeHTTP calls f(w, r). </p>
<h2 id="Header">type <span>Header</span>  </h2> <p>A Header represents the key-value pairs in an HTTP header. </p>
<p>The keys should be in canonical form, as returned by <a href="#CanonicalHeaderKey">CanonicalHeaderKey</a>. </p>
<pre data-language="go">type Header map[string][]string</pre> <h3 id="Header.Add">func (Header) <span>Add</span>  </h3> <pre data-language="go">func (h Header) Add(key, value string)</pre> <p>Add adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by <a href="#CanonicalHeaderKey">CanonicalHeaderKey</a>. </p>
<h3 id="Header.Clone">func (Header) <span>Clone</span>  <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func (h Header) Clone() Header</pre> <p>Clone returns a copy of h or nil if h is nil. </p>
<h3 id="Header.Del">func (Header) <span>Del</span>  </h3> <pre data-language="go">func (h Header) Del(key string)</pre> <p>Del deletes the values associated with key. The key is case insensitive; it is canonicalized by <a href="#CanonicalHeaderKey">CanonicalHeaderKey</a>. </p>
<h3 id="Header.Get">func (Header) <span>Get</span>  </h3> <pre data-language="go">func (h Header) Get(key string) string</pre> <p>Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; <span>textproto.CanonicalMIMEHeaderKey</span> is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form. To use non-canonical keys, access the map directly. </p>
<h3 id="Header.Set">func (Header) <span>Set</span>  </h3> <pre data-language="go">func (h Header) Set(key, value string)</pre> <p>Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by <span>textproto.CanonicalMIMEHeaderKey</span>. To use non-canonical keys, assign to the map directly. </p>
<h3 id="Header.Values">func (Header) <span>Values</span>  <span title="Added in Go 1.14">1.14</span> </h3> <pre data-language="go">func (h Header) Values(key string) []string</pre> <p>Values returns all values associated with the given key. It is case insensitive; <span>textproto.CanonicalMIMEHeaderKey</span> is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy. </p>
<h3 id="Header.Write">func (Header) <span>Write</span>  </h3> <pre data-language="go">func (h Header) Write(w io.Writer) error</pre> <p>Write writes a header in wire format. </p>
<h3 id="Header.WriteSubset">func (Header) <span>WriteSubset</span>  </h3> <pre data-language="go">func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error</pre> <p>WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written. Keys are not canonicalized before checking the exclude map. </p>
<h2 id="Hijacker">type <span>Hijacker</span>  </h2> <p>The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler to take over the connection. </p>
<p>The default <a href="#ResponseWriter">ResponseWriter</a> for HTTP/1.x connections supports Hijacker, but HTTP/2 connections intentionally do not. ResponseWriter wrappers may also not support Hijacker. Handlers should always test for this ability at runtime. </p>
<pre data-language="go">type Hijacker interface {
    // Hijack lets the caller take over the connection.
    // After a call to Hijack the HTTP server library
    // will not do anything else with the connection.
    //
    // It becomes the caller's responsibility to manage
    // and close the connection.
    //
    // The returned net.Conn may have read or write deadlines
    // already set, depending on the configuration of the
    // Server. It is the caller's responsibility to set
    // or clear those deadlines as needed.
    //
    // The returned bufio.Reader may contain unprocessed buffered
    // data from the client.
    //
    // After a call to Hijack, the original Request.Body must not
    // be used. The original Request's Context remains valid and
    // is not canceled until the Request's ServeHTTP method
    // returns.
    Hijack() (net.Conn, *bufio.ReadWriter, error)
}</pre>    <h4 id="example_Hijacker"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
    hj, ok := w.(http.Hijacker)
    if !ok {
        http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
        return
    }
    conn, bufrw, err := hj.Hijack()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // Don't forget to close the connection:
    defer conn.Close()
    bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
    bufrw.Flush()
    s, err := bufrw.ReadString('\n')
    if err != nil {
        log.Printf("error reading string: %v", err)
        return
    }
    fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
    bufrw.Flush()
})
</pre>   <h2 id="MaxBytesError">type <span>MaxBytesError</span>  <span title="Added in Go 1.19">1.19</span> </h2> <p>MaxBytesError is returned by <a href="#MaxBytesReader">MaxBytesReader</a> when its read limit is exceeded. </p>
<pre data-language="go">type MaxBytesError struct {
    Limit int64
}
</pre> <h3 id="MaxBytesError.Error">func (*MaxBytesError) <span>Error</span>  <span title="Added in Go 1.19">1.19</span> </h3> <pre data-language="go">func (e *MaxBytesError) Error() string</pre> <h2 id="ProtocolError">type <span>ProtocolError</span>  </h2> <p>ProtocolError represents an HTTP protocol error. </p>
<p>Deprecated: Not all errors in the http package related to protocol errors are of type ProtocolError. </p>
<pre data-language="go">type ProtocolError struct {
    ErrorString string
}
</pre> <h3 id="ProtocolError.Error">func (*ProtocolError) <span>Error</span>  </h3> <pre data-language="go">func (pe *ProtocolError) Error() string</pre> <h3 id="ProtocolError.Is">func (*ProtocolError) <span>Is</span>  <span title="Added in Go 1.21">1.21</span> </h3> <pre data-language="go">func (pe *ProtocolError) Is(err error) bool</pre> <p>Is lets http.ErrNotSupported match errors.ErrUnsupported. </p>
<h2 id="PushOptions">type <span>PushOptions</span>  <span title="Added in Go 1.8">1.8</span> </h2> <p>PushOptions describes options for [Pusher.Push]. </p>
<pre data-language="go">type PushOptions struct {
    // Method specifies the HTTP method for the promised request.
    // If set, it must be "GET" or "HEAD". Empty means "GET".
    Method string

    // Header specifies additional promised request headers. This cannot
    // include HTTP/2 pseudo header fields like ":path" and ":scheme",
    // which will be added automatically.
    Header Header
}
</pre> <h2 id="Pusher">type <span>Pusher</span>  <span title="Added in Go 1.8">1.8</span> </h2> <p>Pusher is the interface implemented by ResponseWriters that support HTTP/2 server push. For more background, see <a href="https://tools.ietf.org/html/rfc7540#section-8.2">https://tools.ietf.org/html/rfc7540#section-8.2</a>. </p>
<pre data-language="go">type Pusher interface {
    // Push initiates an HTTP/2 server push. This constructs a synthetic
    // request using the given target and options, serializes that request
    // into a PUSH_PROMISE frame, then dispatches that request using the
    // server's request handler. If opts is nil, default options are used.
    //
    // The target must either be an absolute path (like "/path") or an absolute
    // URL that contains a valid host and the same scheme as the parent request.
    // If the target is a path, it will inherit the scheme and host of the
    // parent request.
    //
    // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
    // Push may or may not detect these invalid pushes; however, invalid
    // pushes will be detected and canceled by conforming clients.
    //
    // Handlers that wish to push URL X should call Push before sending any
    // data that may trigger a request for URL X. This avoids a race where the
    // client issues requests for X before receiving the PUSH_PROMISE for X.
    //
    // Push will run in a separate goroutine making the order of arrival
    // non-deterministic. Any required synchronization needs to be implemented
    // by the caller.
    //
    // Push returns ErrNotSupported if the client has disabled push or if push
    // is not supported on the underlying connection.
    Push(target string, opts *PushOptions) error
}</pre> <h2 id="Request">type <span>Request</span>  </h2> <p>A Request represents an HTTP request received by a server or to be sent by a client. </p>
<p>The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for <a href="#Request.Write">Request.Write</a> and <a href="#RoundTripper">RoundTripper</a>. </p>
<pre data-language="go">type Request struct {
    // Method specifies the HTTP method (GET, POST, PUT, etc.).
    // For client requests, an empty string means GET.
    Method string

    // URL specifies either the URI being requested (for server
    // requests) or the URL to access (for client requests).
    //
    // For server requests, the URL is parsed from the URI
    // supplied on the Request-Line as stored in RequestURI.  For
    // most requests, fields other than Path and RawQuery will be
    // empty. (See RFC 7230, Section 5.3)
    //
    // For client requests, the URL's Host specifies the server to
    // connect to, while the Request's Host field optionally
    // specifies the Host header value to send in the HTTP
    // request.
    URL *url.URL

    // The protocol version for incoming server requests.
    //
    // For client requests, these fields are ignored. The HTTP
    // client code always uses either HTTP/1.1 or HTTP/2.
    // See the docs on Transport for details.
    Proto      string // "HTTP/1.0"
    ProtoMajor int    // 1
    ProtoMinor int    // 0

    // Header contains the request header fields either received
    // by the server or to be sent by the client.
    //
    // If a server received a request with header lines,
    //
    //	Host: example.com
    //	accept-encoding: gzip, deflate
    //	Accept-Language: en-us
    //	fOO: Bar
    //	foo: two
    //
    // then
    //
    //	Header = map[string][]string{
    //		"Accept-Encoding": {"gzip, deflate"},
    //		"Accept-Language": {"en-us"},
    //		"Foo": {"Bar", "two"},
    //	}
    //
    // For incoming requests, the Host header is promoted to the
    // Request.Host field and removed from the Header map.
    //
    // HTTP defines that header names are case-insensitive. The
    // request parser implements this by using CanonicalHeaderKey,
    // making the first character and any characters following a
    // hyphen uppercase and the rest lowercase.
    //
    // For client requests, certain headers such as Content-Length
    // and Connection are automatically written when needed and
    // values in Header may be ignored. See the documentation
    // for the Request.Write method.
    Header Header

    // Body is the request's body.
    //
    // For client requests, a nil body means the request has no
    // body, such as a GET request. The HTTP Client's Transport
    // is responsible for calling the Close method.
    //
    // For server requests, the Request Body is always non-nil
    // but will return EOF immediately when no body is present.
    // The Server will close the request body. The ServeHTTP
    // Handler does not need to.
    //
    // Body must allow Read to be called concurrently with Close.
    // In particular, calling Close should unblock a Read waiting
    // for input.
    Body io.ReadCloser

    // GetBody defines an optional func to return a new copy of
    // Body. It is used for client requests when a redirect requires
    // reading the body more than once. Use of GetBody still
    // requires setting Body.
    //
    // For server requests, it is unused.
    GetBody func() (io.ReadCloser, error) // Go 1.8

    // ContentLength records the length of the associated content.
    // The value -1 indicates that the length is unknown.
    // Values &gt;= 0 indicate that the given number of bytes may
    // be read from Body.
    //
    // For client requests, a value of 0 with a non-nil Body is
    // also treated as unknown.
    ContentLength int64

    // TransferEncoding lists the transfer encodings from outermost to
    // innermost. An empty list denotes the "identity" encoding.
    // TransferEncoding can usually be ignored; chunked encoding is
    // automatically added and removed as necessary when sending and
    // receiving requests.
    TransferEncoding []string

    // Close indicates whether to close the connection after
    // replying to this request (for servers) or after sending this
    // request and reading its response (for clients).
    //
    // For server requests, the HTTP server handles this automatically
    // and this field is not needed by Handlers.
    //
    // For client requests, setting this field prevents re-use of
    // TCP connections between requests to the same hosts, as if
    // Transport.DisableKeepAlives were set.
    Close bool

    // For server requests, Host specifies the host on which the
    // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
    // is either the value of the "Host" header or the host name
    // given in the URL itself. For HTTP/2, it is the value of the
    // ":authority" pseudo-header field.
    // It may be of the form "host:port". For international domain
    // names, Host may be in Punycode or Unicode form. Use
    // golang.org/x/net/idna to convert it to either format if
    // needed.
    // To prevent DNS rebinding attacks, server Handlers should
    // validate that the Host header has a value for which the
    // Handler considers itself authoritative. The included
    // ServeMux supports patterns registered to particular host
    // names and thus protects its registered Handlers.
    //
    // For client requests, Host optionally overrides the Host
    // header to send. If empty, the Request.Write method uses
    // the value of URL.Host. Host may contain an international
    // domain name.
    Host string

    // Form contains the parsed form data, including both the URL
    // field's query parameters and the PATCH, POST, or PUT form data.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores Form and uses Body instead.
    Form url.Values

    // PostForm contains the parsed form data from PATCH, POST
    // or PUT body parameters.
    //
    // This field is only available after ParseForm is called.
    // The HTTP client ignores PostForm and uses Body instead.
    PostForm url.Values // Go 1.1

    // MultipartForm is the parsed multipart form, including file uploads.
    // This field is only available after ParseMultipartForm is called.
    // The HTTP client ignores MultipartForm and uses Body instead.
    MultipartForm *multipart.Form

    // Trailer specifies additional headers that are sent after the request
    // body.
    //
    // For server requests, the Trailer map initially contains only the
    // trailer keys, with nil values. (The client declares which trailers it
    // will later send.)  While the handler is reading from Body, it must
    // not reference Trailer. After reading from Body returns EOF, Trailer
    // can be read again and will contain non-nil values, if they were sent
    // by the client.
    //
    // For client requests, Trailer must be initialized to a map containing
    // the trailer keys to later send. The values may be nil or their final
    // values. The ContentLength must be 0 or -1, to send a chunked request.
    // After the HTTP request is sent the map values can be updated while
    // the request body is read. Once the body returns EOF, the caller must
    // not mutate Trailer.
    //
    // Few HTTP clients, servers, or proxies support HTTP trailers.
    Trailer Header

    // RemoteAddr allows HTTP servers and other software to record
    // the network address that sent the request, usually for
    // logging. This field is not filled in by ReadRequest and
    // has no defined format. The HTTP server in this package
    // sets RemoteAddr to an "IP:port" address before invoking a
    // handler.
    // This field is ignored by the HTTP client.
    RemoteAddr string

    // RequestURI is the unmodified request-target of the
    // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
    // to a server. Usually the URL field should be used instead.
    // It is an error to set this field in an HTTP client request.
    RequestURI string

    // TLS allows HTTP servers and other software to record
    // information about the TLS connection on which the request
    // was received. This field is not filled in by ReadRequest.
    // The HTTP server in this package sets the field for
    // TLS-enabled connections before invoking a handler;
    // otherwise it leaves the field nil.
    // This field is ignored by the HTTP client.
    TLS *tls.ConnectionState

    // Cancel is an optional channel whose closure indicates that the client
    // request should be regarded as canceled. Not all implementations of
    // RoundTripper may support Cancel.
    //
    // For server requests, this field is not applicable.
    //
    // Deprecated: Set the Request's context with NewRequestWithContext
    // instead. If a Request's Cancel field and context are both
    // set, it is undefined whether Cancel is respected.
    Cancel &lt;-chan struct{} // Go 1.5

    // Response is the redirect response which caused this request
    // to be created. This field is only populated during client
    // redirects.
    Response *Response // Go 1.7
    // contains filtered or unexported fields
}
</pre> <h3 id="NewRequest">func <span>NewRequest</span>  </h3> <pre data-language="go">func NewRequest(method, url string, body io.Reader) (*Request, error)</pre> <p>NewRequest wraps <a href="#NewRequestWithContext">NewRequestWithContext</a> using <span>context.Background</span>. </p>
<h3 id="NewRequestWithContext">func <span>NewRequestWithContext</span>  <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)</pre> <p>NewRequestWithContext returns a new <a href="#Request">Request</a> given a method, URL, and optional body. </p>
<p>If the provided body is also an <span>io.Closer</span>, the returned [Request.Body] is set to body and will be closed (possibly asynchronously) by the Client methods Do, Post, and PostForm, and <a href="#Transport.RoundTrip">Transport.RoundTrip</a>. </p>
<p>NewRequestWithContext returns a Request suitable for use with <a href="#Client.Do">Client.Do</a> or <a href="#Transport.RoundTrip">Transport.RoundTrip</a>. To create a request for use with testing a Server Handler, either use the <a href="#NewRequest">NewRequest</a> function in the net/http/httptest package, use <a href="#ReadRequest">ReadRequest</a>, or manually update the Request fields. For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. See the Request type's documentation for the difference between inbound and outbound request fields. </p>
<p>If body is of type <span>*bytes.Buffer</span>, <span>*bytes.Reader</span>, or <span>*strings.Reader</span>, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to <a href="#NoBody">NoBody</a> if the ContentLength is 0. </p>
<h3 id="ReadRequest">func <span>ReadRequest</span>  </h3> <pre data-language="go">func ReadRequest(b *bufio.Reader) (*Request, error)</pre> <p>ReadRequest reads and parses an incoming request from b. </p>
<p>ReadRequest is a low-level function and should only be used for specialized applications; most code should use the <a href="#Server">Server</a> to read requests and handle them via the <a href="#Handler">Handler</a> interface. ReadRequest only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2. </p>
<h3 id="Request.AddCookie">func (*Request) <span>AddCookie</span>  </h3> <pre data-language="go">func (r *Request) AddCookie(c *Cookie)</pre> <p>AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one <a href="#Cookie">Cookie</a> header field. That means all cookies, if any, are written into the same line, separated by semicolon. AddCookie only sanitizes c's name and value, and does not sanitize a Cookie header already present in the request. </p>
<h3 id="Request.BasicAuth">func (*Request) <span>BasicAuth</span>  <span title="Added in Go 1.4">1.4</span> </h3> <pre data-language="go">func (r *Request) BasicAuth() (username, password string, ok bool)</pre> <p>BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2. </p>
<h3 id="Request.Clone">func (*Request) <span>Clone</span>  <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func (r *Request) Clone(ctx context.Context) *Request</pre> <p>Clone returns a deep copy of r with its context changed to ctx. The provided ctx must be non-nil. </p>
<p>For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. </p>
<h3 id="Request.Context">func (*Request) <span>Context</span>  <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (r *Request) Context() context.Context</pre> <p>Context returns the request's context. To change the context, use <a href="#Request.Clone">Request.Clone</a> or <a href="#Request.WithContext">Request.WithContext</a>. </p>
<p>The returned context is always non-nil; it defaults to the background context. </p>
<p>For outgoing client requests, the context controls cancellation. </p>
<p>For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns. </p>
<h3 id="Request.Cookie">func (*Request) <span>Cookie</span>  </h3> <pre data-language="go">func (r *Request) Cookie(name string) (*Cookie, error)</pre> <p>Cookie returns the named cookie provided in the request or <a href="#ErrNoCookie">ErrNoCookie</a> if not found. If multiple cookies match the given name, only one cookie will be returned. </p>
<h3 id="Request.Cookies">func (*Request) <span>Cookies</span>  </h3> <pre data-language="go">func (r *Request) Cookies() []*Cookie</pre> <p>Cookies parses and returns the HTTP cookies sent with the request. </p>
<h3 id="Request.FormFile">func (*Request) <span>FormFile</span>  </h3> <pre data-language="go">func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)</pre> <p>FormFile returns the first file for the provided form key. FormFile calls <a href="#Request.ParseMultipartForm">Request.ParseMultipartForm</a> and <a href="#Request.ParseForm">Request.ParseForm</a> if necessary. </p>
<h3 id="Request.FormValue">func (*Request) <span>FormValue</span>  </h3> <pre data-language="go">func (r *Request) FormValue(key string) string</pre> <p>FormValue returns the first value for the named component of the query. The precedence order: </p>
<ol> <li>application/x-www-form-urlencoded form body (POST, PUT, PATCH only) </li>
<li>query parameters (always) </li>
<li>multipart/form-data form body (always) </li>
</ol> <p>FormValue calls <a href="#Request.ParseMultipartForm">Request.ParseMultipartForm</a> and <a href="#Request.ParseForm">Request.ParseForm</a> if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect [Request.Form] directly. </p>
<h3 id="Request.MultipartReader">func (*Request) <span>MultipartReader</span>  </h3> <pre data-language="go">func (r *Request) MultipartReader() (*multipart.Reader, error)</pre> <p>MultipartReader returns a MIME multipart reader if this is a multipart/form-data or a multipart/mixed POST request, else returns nil and an error. Use this function instead of <a href="#Request.ParseMultipartForm">Request.ParseMultipartForm</a> to process the request body as a stream. </p>
<h3 id="Request.ParseForm">func (*Request) <span>ParseForm</span>  </h3> <pre data-language="go">func (r *Request) ParseForm() error</pre> <p>ParseForm populates r.Form and r.PostForm. </p>
<p>For all requests, ParseForm parses the raw query from the URL and updates r.Form. </p>
<p>For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form. </p>
<p>If the request Body's size has not already been limited by <a href="#MaxBytesReader">MaxBytesReader</a>, the size is capped at 10MB. </p>
<p>For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value. </p>
<p><a href="#Request.ParseMultipartForm">Request.ParseMultipartForm</a> calls ParseForm automatically. ParseForm is idempotent. </p>
<h3 id="Request.ParseMultipartForm">func (*Request) <span>ParseMultipartForm</span>  </h3> <pre data-language="go">func (r *Request) ParseMultipartForm(maxMemory int64) error</pre> <p>ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls <a href="#Request.ParseForm">Request.ParseForm</a> if necessary. If ParseForm returns an error, ParseMultipartForm returns it but also continues parsing the request body. After one call to ParseMultipartForm, subsequent calls have no effect. </p>
<h3 id="Request.PathValue">func (*Request) <span>PathValue</span>  <span title="Added in Go 1.22">1.22</span> </h3> <pre data-language="go">func (r *Request) PathValue(name string) string</pre> <p>PathValue returns the value for the named path wildcard in the <a href="#ServeMux">ServeMux</a> pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern. </p>
<h3 id="Request.PostFormValue">func (*Request) <span>PostFormValue</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (r *Request) PostFormValue(key string) string</pre> <p>PostFormValue returns the first value for the named component of the POST, PUT, or PATCH request body. URL query parameters are ignored. PostFormValue calls <a href="#Request.ParseMultipartForm">Request.ParseMultipartForm</a> and <a href="#Request.ParseForm">Request.ParseForm</a> if necessary and ignores any errors returned by these functions. If key is not present, PostFormValue returns the empty string. </p>
<h3 id="Request.ProtoAtLeast">func (*Request) <span>ProtoAtLeast</span>  </h3> <pre data-language="go">func (r *Request) ProtoAtLeast(major, minor int) bool</pre> <p>ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor. </p>
<h3 id="Request.Referer">func (*Request) <span>Referer</span>  </h3> <pre data-language="go">func (r *Request) Referer() string</pre> <p>Referer returns the referring URL, if sent in the request. </p>
<p>Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the <a href="#Header">Header</a> map as Header["Referer"]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header["Referrer"]. </p>
<h3 id="Request.SetBasicAuth">func (*Request) <span>SetBasicAuth</span>  </h3> <pre data-language="go">func (r *Request) SetBasicAuth(username, password string)</pre> <p>SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password. </p>
<p>With HTTP Basic Authentication the provided username and password are not encrypted. It should generally only be used in an HTTPS request. </p>
<p>The username may not contain a colon. Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with <span>url.QueryEscape</span>. </p>
<h3 id="Request.SetPathValue">func (*Request) <span>SetPathValue</span>  <span title="Added in Go 1.22">1.22</span> </h3> <pre data-language="go">func (r *Request) SetPathValue(name, value string)</pre> <p>SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) return value. </p>
<h3 id="Request.UserAgent">func (*Request) <span>UserAgent</span>  </h3> <pre data-language="go">func (r *Request) UserAgent() string</pre> <p>UserAgent returns the client's User-Agent, if sent in the request. </p>
<h3 id="Request.WithContext">func (*Request) <span>WithContext</span>  <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (r *Request) WithContext(ctx context.Context) *Request</pre> <p>WithContext returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil. </p>
<p>For outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. </p>
<p>To create a new request with a context, use <a href="#NewRequestWithContext">NewRequestWithContext</a>. To make a deep copy of a request with a new context, use <a href="#Request.Clone">Request.Clone</a>. </p>
<h3 id="Request.Write">func (*Request) <span>Write</span>  </h3> <pre data-language="go">func (r *Request) Write(w io.Writer) error</pre> <p>Write writes an HTTP/1.1 request, which is the header and body, in wire format. This method consults the following fields of the request: </p>
<pre data-language="go">Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body
</pre> <p>If Body is present, Content-Length is &lt;= 0 and [Request.TransferEncoding] hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent. </p>
<h3 id="Request.WriteProxy">func (*Request) <span>WriteProxy</span>  </h3> <pre data-language="go">func (r *Request) WriteProxy(w io.Writer) error</pre> <p>WriteProxy is like <a href="#Request.Write">Request.Write</a> but writes the request in the form expected by an HTTP proxy. In particular, <a href="#Request.WriteProxy">Request.WriteProxy</a> writes the initial Request-URI line of the request with an absolute URI, per section 5.3 of RFC 7230, including the scheme and host. In either case, WriteProxy also writes a Host header, using either r.Host or r.URL.Host. </p>
<h2 id="Response">type <span>Response</span>  </h2> <p>Response represents the response from an HTTP request. </p>
<p>The <a href="#Client">Client</a> and <a href="#Transport">Transport</a> return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read. </p>
<pre data-language="go">type Response struct {
    Status     string // e.g. "200 OK"
    StatusCode int    // e.g. 200
    Proto      string // e.g. "HTTP/1.0"
    ProtoMajor int    // e.g. 1
    ProtoMinor int    // e.g. 0

    // Header maps header keys to values. If the response had multiple
    // headers with the same key, they may be concatenated, with comma
    // delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
    // be semantically equivalent to a comma-delimited sequence.) When
    // Header values are duplicated by other fields in this struct (e.g.,
    // ContentLength, TransferEncoding, Trailer), the field values are
    // authoritative.
    //
    // Keys in the map are canonicalized (see CanonicalHeaderKey).
    Header Header

    // Body represents the response body.
    //
    // The response body is streamed on demand as the Body field
    // is read. If the network connection fails or the server
    // terminates the response, Body.Read calls return an error.
    //
    // The http Client and Transport guarantee that Body is always
    // non-nil, even on responses without a body or responses with
    // a zero-length body. It is the caller's responsibility to
    // close Body. The default HTTP client's Transport may not
    // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
    // not read to completion and closed.
    //
    // The Body is automatically dechunked if the server replied
    // with a "chunked" Transfer-Encoding.
    //
    // As of Go 1.12, the Body will also implement io.Writer
    // on a successful "101 Switching Protocols" response,
    // as used by WebSockets and HTTP/2's "h2c" mode.
    Body io.ReadCloser

    // ContentLength records the length of the associated content. The
    // value -1 indicates that the length is unknown. Unless Request.Method
    // is "HEAD", values &gt;= 0 indicate that the given number of bytes may
    // be read from Body.
    ContentLength int64

    // Contains transfer encodings from outer-most to inner-most. Value is
    // nil, means that "identity" encoding is used.
    TransferEncoding []string

    // Close records whether the header directed that the connection be
    // closed after reading Body. The value is advice for clients: neither
    // ReadResponse nor Response.Write ever closes a connection.
    Close bool

    // Uncompressed reports whether the response was sent compressed but
    // was decompressed by the http package. When true, reading from
    // Body yields the uncompressed content instead of the compressed
    // content actually set from the server, ContentLength is set to -1,
    // and the "Content-Length" and "Content-Encoding" fields are deleted
    // from the responseHeader. To get the original response from
    // the server, set Transport.DisableCompression to true.
    Uncompressed bool // Go 1.7

    // Trailer maps trailer keys to values in the same
    // format as Header.
    //
    // The Trailer initially contains only nil values, one for
    // each key specified in the server's "Trailer" header
    // value. Those values are not added to Header.
    //
    // Trailer must not be accessed concurrently with Read calls
    // on the Body.
    //
    // After Body.Read has returned io.EOF, Trailer will contain
    // any trailer values sent by the server.
    Trailer Header

    // Request is the request that was sent to obtain this Response.
    // Request's Body is nil (having already been consumed).
    // This is only populated for Client requests.
    Request *Request

    // TLS contains information about the TLS connection on which the
    // response was received. It is nil for unencrypted responses.
    // The pointer is shared between responses and should not be
    // modified.
    TLS *tls.ConnectionState // Go 1.3
}
</pre> <h3 id="Get">func <span>Get</span>  </h3> <pre data-language="go">func Get(url string) (resp *Response, err error)</pre> <p>Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects: </p>
<pre data-language="go">301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
</pre> <p>An error is returned if there were too many redirects or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type <span>*url.Error</span>. The url.Error value's Timeout method will report true if the request timed out. </p>
<p>When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. </p>
<p>Get is a wrapper around DefaultClient.Get. </p>
<p>To make a request with custom headers, use <a href="#NewRequest">NewRequest</a> and DefaultClient.Do. </p>
<p>To make a request with a specified context.Context, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and DefaultClient.Do. </p>   <h4 id="example_Get"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
    log.Fatal(err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode &gt; 299 {
    log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
}
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%s", body)
</pre>   <h3 id="Head">func <span>Head</span>  </h3> <pre data-language="go">func Head(url string) (resp *Response, err error)</pre> <p>Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect, up to a maximum of 10 redirects: </p>
<pre data-language="go">301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
</pre> <p>Head is a wrapper around DefaultClient.Head. </p>
<p>To make a request with a specified <span>context.Context</span>, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and DefaultClient.Do. </p>
<h3 id="Post">func <span>Post</span>  </h3> <pre data-language="go">func Post(url, contentType string, body io.Reader) (resp *Response, err error)</pre> <p>Post issues a POST to the specified URL. </p>
<p>Caller should close resp.Body when done reading from it. </p>
<p>If the provided body is an <span>io.Closer</span>, it is closed after the request. </p>
<p>Post is a wrapper around DefaultClient.Post. </p>
<p>To set custom headers, use <a href="#NewRequest">NewRequest</a> and DefaultClient.Do. </p>
<p>See the <a href="#Client.Do">Client.Do</a> method documentation for details on how redirects are handled. </p>
<p>To make a request with a specified context.Context, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and DefaultClient.Do. </p>
<h3 id="PostForm">func <span>PostForm</span>  </h3> <pre data-language="go">func PostForm(url string, data url.Values) (resp *Response, err error)</pre> <p>PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body. </p>
<p>The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use <a href="#NewRequest">NewRequest</a> and DefaultClient.Do. </p>
<p>When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. </p>
<p>PostForm is a wrapper around DefaultClient.PostForm. </p>
<p>See the <a href="#Client.Do">Client.Do</a> method documentation for details on how redirects are handled. </p>
<p>To make a request with a specified <span>context.Context</span>, use <a href="#NewRequestWithContext">NewRequestWithContext</a> and DefaultClient.Do. </p>
<h3 id="ReadResponse">func <span>ReadResponse</span>  </h3> <pre data-language="go">func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)</pre> <p>ReadResponse reads and returns an HTTP response from r. The req parameter optionally specifies the <a href="#Request">Request</a> that corresponds to this <a href="#Response">Response</a>. If nil, a GET request is assumed. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer. </p>
<h3 id="Response.Cookies">func (*Response) <span>Cookies</span>  </h3> <pre data-language="go">func (r *Response) Cookies() []*Cookie</pre> <p>Cookies parses and returns the cookies set in the Set-Cookie headers. </p>
<h3 id="Response.Location">func (*Response) <span>Location</span>  </h3> <pre data-language="go">func (r *Response) Location() (*url.URL, error)</pre> <p>Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to [Response.Request]. <a href="#ErrNoLocation">ErrNoLocation</a> is returned if no Location header is present. </p>
<h3 id="Response.ProtoAtLeast">func (*Response) <span>ProtoAtLeast</span>  </h3> <pre data-language="go">func (r *Response) ProtoAtLeast(major, minor int) bool</pre> <p>ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor. </p>
<h3 id="Response.Write">func (*Response) <span>Write</span>  </h3> <pre data-language="go">func (r *Response) Write(w io.Writer) error</pre> <p>Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer. </p>
<p>This method consults the following fields of the response r: </p>
<pre data-language="go">StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior
</pre> <p>The Response Body is closed after it is sent. </p>
<h2 id="ResponseController">type <span>ResponseController</span>  <span title="Added in Go 1.20">1.20</span> </h2> <p>A ResponseController is used by an HTTP handler to control the response. </p>
<p>A ResponseController may not be used after the [Handler.ServeHTTP] method has returned. </p>
<pre data-language="go">type ResponseController struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewResponseController">func <span>NewResponseController</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func NewResponseController(rw ResponseWriter) *ResponseController</pre> <p>NewResponseController creates a <a href="#ResponseController">ResponseController</a> for a request. </p>
<p>The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter. </p>
<p>If the ResponseWriter implements any of the following methods, the ResponseController will call them as appropriate: </p>
<pre data-language="go">Flush()
FlushError() error // alternative Flush returning an error
Hijack() (net.Conn, *bufio.ReadWriter, error)
SetReadDeadline(deadline time.Time) error
SetWriteDeadline(deadline time.Time) error
EnableFullDuplex() error
</pre> <p>If the ResponseWriter does not support a method, ResponseController returns an error matching <a href="#ErrNotSupported">ErrNotSupported</a>. </p>
<h3 id="ResponseController.EnableFullDuplex">func (*ResponseController) <span>EnableFullDuplex</span>  <span title="Added in Go 1.21">1.21</span> </h3> <pre data-language="go">func (c *ResponseController) EnableFullDuplex() error</pre> <p>EnableFullDuplex indicates that the request handler will interleave reads from [Request.Body] with writes to the <a href="#ResponseWriter">ResponseWriter</a>. </p>
<p>For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of the request body before beginning to write the response, preventing handlers from concurrently reading from the request and writing the response. Calling EnableFullDuplex disables this behavior and permits handlers to continue to read from the request while concurrently writing the response. </p>
<p>For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses. </p>
<h3 id="ResponseController.Flush">func (*ResponseController) <span>Flush</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (c *ResponseController) Flush() error</pre> <p>Flush flushes buffered data to the client. </p>
<h3 id="ResponseController.Hijack">func (*ResponseController) <span>Hijack</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)</pre> <p>Hijack lets the caller take over the connection. See the Hijacker interface for details. </p>
<h3 id="ResponseController.SetReadDeadline">func (*ResponseController) <span>SetReadDeadline</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (c *ResponseController) SetReadDeadline(deadline time.Time) error</pre> <p>SetReadDeadline sets the deadline for reading the entire request, including the body. Reads from the request body after the deadline has been exceeded will return an error. A zero value means no deadline. </p>
<p>Setting the read deadline after it has been exceeded will not extend it. </p>
<h3 id="ResponseController.SetWriteDeadline">func (*ResponseController) <span>SetWriteDeadline</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (c *ResponseController) SetWriteDeadline(deadline time.Time) error</pre> <p>SetWriteDeadline sets the deadline for writing the response. Writes to the response body after the deadline has been exceeded will not block, but may succeed if the data has been buffered. A zero value means no deadline. </p>
<p>Setting the write deadline after it has been exceeded will not extend it. </p>
<h2 id="ResponseWriter">type <span>ResponseWriter</span>  </h2> <p>A ResponseWriter interface is used by an HTTP handler to construct an HTTP response. </p>
<p>A ResponseWriter may not be used after [Handler.ServeHTTP] has returned. </p>
<pre data-language="go">type ResponseWriter interface {
    // Header returns the header map that will be sent by
    // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
    // [Handler] implementations can set HTTP trailers.
    //
    // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
    // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
    // 1xx class or the modified headers are trailers.
    //
    // There are two ways to set Trailers. The preferred way is to
    // predeclare in the headers which trailers you will later
    // send by setting the "Trailer" header to the names of the
    // trailer keys which will come later. In this case, those
    // keys of the Header map are treated as if they were
    // trailers. See the example. The second way, for trailer
    // keys not known to the [Handler] until after the first [ResponseWriter.Write],
    // is to prefix the [Header] map keys with the [TrailerPrefix]
    // constant value.
    //
    // To suppress automatic response headers (such as "Date"), set
    // their value to nil.
    Header() Header

    // Write writes the data to the connection as part of an HTTP reply.
    //
    // If [ResponseWriter.WriteHeader] has not yet been called, Write calls
    // WriteHeader(http.StatusOK) before writing the data. If the Header
    // does not contain a Content-Type line, Write adds a Content-Type set
    // to the result of passing the initial 512 bytes of written data to
    // [DetectContentType]. Additionally, if the total size of all written
    // data is under a few KB and there are no Flush calls, the
    // Content-Length header is added automatically.
    //
    // Depending on the HTTP protocol version and the client, calling
    // Write or WriteHeader may prevent future reads on the
    // Request.Body. For HTTP/1.x requests, handlers should read any
    // needed request body data before writing the response. Once the
    // headers have been flushed (due to either an explicit Flusher.Flush
    // call or writing enough data to trigger a flush), the request body
    // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
    // handlers to continue to read the request body while concurrently
    // writing the response. However, such behavior may not be supported
    // by all HTTP/2 clients. Handlers should read before writing if
    // possible to maximize compatibility.
    Write([]byte) (int, error)

    // WriteHeader sends an HTTP response header with the provided
    // status code.
    //
    // If WriteHeader is not called explicitly, the first call to Write
    // will trigger an implicit WriteHeader(http.StatusOK).
    // Thus explicit calls to WriteHeader are mainly used to
    // send error codes or 1xx informational responses.
    //
    // The provided code must be a valid HTTP 1xx-5xx status code.
    // Any number of 1xx headers may be written, followed by at most
    // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
    // headers may be buffered. Use the Flusher interface to send
    // buffered data. The header map is cleared when 2xx-5xx headers are
    // sent, but not with 1xx headers.
    //
    // The server will automatically send a 100 (Continue) header
    // on the first read from the request body if the request has
    // an "Expect: 100-continue" header.
    WriteHeader(statusCode int)
}</pre>    <h4 id="example_ResponseWriter_trailers"> <span class="text">Example (Trailers)</span>
</h4> <p>HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before. </p> <p>Code:</p> <pre class="code" data-language="go">
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
    // Before any call to WriteHeader or Write, declare
    // the trailers you will set during the HTTP
    // response. These three headers are actually sent in
    // the trailer.
    w.Header().Set("Trailer", "AtEnd1, AtEnd2")
    w.Header().Add("Trailer", "AtEnd3")

    w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
    w.WriteHeader(http.StatusOK)

    w.Header().Set("AtEnd1", "value 1")
    io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
    w.Header().Set("AtEnd2", "value 2")
    w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
})
</pre>   <h2 id="RoundTripper">type <span>RoundTripper</span>  </h2> <p>RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the <a href="#Response">Response</a> for a given <a href="#Request">Request</a>. </p>
<p>A RoundTripper must be safe for concurrent use by multiple goroutines. </p>
<pre data-language="go">type RoundTripper interface {
    // RoundTrip executes a single HTTP transaction, returning
    // a Response for the provided Request.
    //
    // RoundTrip should not attempt to interpret the response. In
    // particular, RoundTrip must return err == nil if it obtained
    // a response, regardless of the response's HTTP status code.
    // A non-nil err should be reserved for failure to obtain a
    // response. Similarly, RoundTrip should not attempt to
    // handle higher-level protocol details such as redirects,
    // authentication, or cookies.
    //
    // RoundTrip should not modify the request, except for
    // consuming and closing the Request's Body. RoundTrip may
    // read fields of the request in a separate goroutine. Callers
    // should not mutate or reuse the request until the Response's
    // Body has been closed.
    //
    // RoundTrip must always close the body, including on errors,
    // but depending on the implementation may do so in a separate
    // goroutine even after RoundTrip returns. This means that
    // callers wanting to reuse the body for subsequent requests
    // must arrange to wait for the Close call before doing so.
    //
    // The Request's URL and Header fields must be initialized.
    RoundTrip(*Request) (*Response, error)
}</pre> <p>DefaultTransport is the default implementation of <a href="#Transport">Transport</a> and is used by <a href="#DefaultClient">DefaultClient</a>. It establishes network connections as needed and caches them for reuse by subsequent calls. It uses HTTP proxies as directed by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). </p>
<pre data-language="go">var DefaultTransport RoundTripper = &amp;Transport{
    Proxy: ProxyFromEnvironment,
    DialContext: defaultTransportDialContext(&amp;net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
    }),
    ForceAttemptHTTP2:     true,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}</pre> <h3 id="NewFileTransport">func <span>NewFileTransport</span>  </h3> <pre data-language="go">func NewFileTransport(fs FileSystem) RoundTripper</pre> <p>NewFileTransport returns a new <a href="#RoundTripper">RoundTripper</a>, serving the provided <a href="#FileSystem">FileSystem</a>. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request. </p>
<p>The typical use case for NewFileTransport is to register the "file" protocol with a <a href="#Transport">Transport</a>, as in: </p>
<pre data-language="go">t := &amp;http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &amp;http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
</pre> <h3 id="NewFileTransportFS">func <span>NewFileTransportFS</span>  <span title="Added in Go 1.22">1.22</span> </h3> <pre data-language="go">func NewFileTransportFS(fsys fs.FS) RoundTripper</pre> <p>NewFileTransportFS returns a new <a href="#RoundTripper">RoundTripper</a>, serving the provided file system fsys. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request. </p>
<p>The typical use case for NewFileTransportFS is to register the "file" protocol with a <a href="#Transport">Transport</a>, as in: </p>
<pre data-language="go">fsys := os.DirFS("/")
t := &amp;http.Transport{}
t.RegisterProtocol("file", http.NewFileTransportFS(fsys))
c := &amp;http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
</pre> <h2 id="SameSite">type <span>SameSite</span>  <span title="Added in Go 1.11">1.11</span> </h2> <p>SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks. </p>
<p>See <a href="https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00">https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00</a> for details. </p>
<pre data-language="go">type SameSite int</pre> <pre data-language="go">const (
    SameSiteDefaultMode SameSite = iota + 1
    SameSiteLaxMode
    SameSiteStrictMode
    SameSiteNoneMode
)</pre> <h2 id="ServeMux">type <span>ServeMux</span>  </h2> <p>ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. </p>
<h3 id="hdr-Patterns">Patterns</h3> <p>Patterns can match the method, host and path of a request. Some examples: </p>
<ul> <li>"/index.html" matches the path "/index.html" for any host and method. </li>
<li>"GET /static/" matches a GET request whose path begins with "/static/". </li>
<li>"example.com/" matches any request to the host "example.com". </li>
<li>"example.com/{$}" matches requests with host "example.com" and path "/". </li>
<li>"/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b" and whose third segment is "o". The name "bucket" denotes the second segment and "objectname" denotes the remainder of the path. </li>
</ul> <p>In general, a pattern looks like </p>
<pre data-language="go">[METHOD ][HOST]/[PATH]
</pre> <p>All three parts are optional; "/" is a valid pattern. If METHOD is present, it must be followed by a single space. </p>
<p>Literal (that is, non-wildcard) parts of a pattern match the corresponding parts of a request case-sensitively. </p>
<p>A pattern with no method matches every method. A pattern with the method GET matches both GET and HEAD requests. Otherwise, the method must match exactly. </p>
<p>A pattern with no host matches every host. A pattern with a host matches URLs on that host only. </p>
<p>A path can include wildcard segments of the form {NAME} or {NAME...}. For example, "/b/{bucket}/o/{objectname...}". The wildcard name must be a valid Go identifier. Wildcards must be full path segments: they must be preceded by a slash and followed by either a slash or the end of the string. For example, "/b_{bucket}" is not a valid pattern. </p>
<p>Normally a wildcard matches only a single path segment, ending at the next literal slash (not %2F) in the request URL. But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes. (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.) The match for a wildcard can be obtained by calling <a href="#Request.PathValue">Request.PathValue</a> with the wildcard's name. A trailing slash in a path acts as an anonymous "..." wildcard. </p>
<p>The special wildcard {$} matches only the end of the URL. For example, the pattern "/{$}" matches only the path "/", whereas the pattern "/" matches every path. </p>
<p>For matching, both pattern paths and incoming request paths are unescaped segment by segment. So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%". The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not. </p>
<h3 id="hdr-Precedence">Precedence</h3> <p>If two or more patterns match a request, then the most specific pattern takes precedence. A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests; that is, if P2 matches all the requests of P1 and more. If neither is more specific, then the patterns conflict. There is one exception to this rule, for backwards compatibility: if two patterns would otherwise conflict and one has a host while the other does not, then the pattern with the host takes precedence. If a pattern passed <a href="#ServeMux.Handle">ServeMux.Handle</a> or <a href="#ServeMux.HandleFunc">ServeMux.HandleFunc</a> conflicts with another pattern that is already registered, those functions panic. </p>
<p>As an example of the general rule, "/images/thumbnails/" is more specific than "/images/", so both can be registered. The former matches paths beginning with "/images/thumbnails/" and the latter will match any other path in the "/images/" subtree. </p>
<p>As another example, consider the patterns "GET /" and "/index.html": both match a GET request for "/index.html", but the former pattern matches all other GET and HEAD requests, while the latter matches any request for "/index.html" that uses a different method. The patterns conflict. </p>
<h3 id="hdr-Trailing_slash_redirection">Trailing-slash redirection</h3> <p>Consider a <a href="#ServeMux">ServeMux</a> with a handler for a subtree, registered using a trailing slash or "..." wildcard. If the ServeMux receives a request for the subtree root without a trailing slash, it redirects the request by adding the trailing slash. This behavior can be overridden with a separate registration for the path without the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately. </p>
<h3 id="hdr-Request_sanitizing">Request sanitizing</h3> <p>ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. segments or repeated slashes to an equivalent, cleaner URL. </p>
<h3 id="hdr-Compatibility">Compatibility</h3> <p>The pattern syntax and matching behavior of ServeMux changed significantly in Go 1.22. To restore the old behavior, set the GODEBUG environment variable to "httpmuxgo121=1". This setting is read once, at program startup; changes during execution will be ignored. </p>
<p>The backwards-incompatible changes include: </p>
<ul> <li>Wildcards are just ordinary literal path segments in 1.21. For example, the pattern "/{x}" will match only that path in 1.21, but will match any one-segment path in 1.22. </li>
<li>In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern. In 1.22, syntactically invalid patterns will cause <a href="#ServeMux.Handle">ServeMux.Handle</a> and <a href="#ServeMux.HandleFunc">ServeMux.HandleFunc</a> to panic. For example, in 1.21, the patterns "/{" and "/a{x}" match themselves, but in 1.22 they are invalid and will cause a panic when registered. </li>
<li>In 1.22, each segment of a pattern is unescaped; this was not done in 1.21. For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"), but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign). </li>
<li>When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped. This change mostly affects how paths with %2F escapes adjacent to slashes are treated. See <a href="https://go.dev/issue/21955">https://go.dev/issue/21955</a> for details. </li>
</ul> <pre data-language="go">type ServeMux struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewServeMux">func <span>NewServeMux</span>  </h3> <pre data-language="go">func NewServeMux() *ServeMux</pre> <p>NewServeMux allocates and returns a new <a href="#ServeMux">ServeMux</a>. </p>
<h3 id="ServeMux.Handle">func (*ServeMux) <span>Handle</span>  </h3> <pre data-language="go">func (mux *ServeMux) Handle(pattern string, handler Handler)</pre> <p>Handle registers the handler for the given pattern. If the given pattern conflicts, with one that is already registered, Handle panics. </p>   <h4 id="example_ServeMux_Handle"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    // The "/" pattern matches everything, so we need to check
    // that we're at the root here.
    if req.URL.Path != "/" {
        http.NotFound(w, req)
        return
    }
    fmt.Fprintf(w, "Welcome to the home page!")
})
</pre>   <h3 id="ServeMux.HandleFunc">func (*ServeMux) <span>HandleFunc</span>  </h3> <pre data-language="go">func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))</pre> <p>HandleFunc registers the handler function for the given pattern. If the given pattern conflicts, with one that is already registered, HandleFunc panics. </p>
<h3 id="ServeMux.Handler">func (*ServeMux) <span>Handler</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)</pre> <p>Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers. </p>
<p>The path and host are used unchanged for CONNECT requests. </p>
<p>Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the path that will match after following the redirect. </p>
<p>If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern. </p>
<h3 id="ServeMux.ServeHTTP">func (*ServeMux) <span>ServeHTTP</span>  </h3> <pre data-language="go">func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)</pre> <p>ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL. </p>
<h2 id="Server">type <span>Server</span>  </h2> <p>A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration. </p>
<pre data-language="go">type Server struct {
    // Addr optionally specifies the TCP address for the server to listen on,
    // in the form "host:port". If empty, ":http" (port 80) is used.
    // The service names are defined in RFC 6335 and assigned by IANA.
    // See net.Dial for details of the address format.
    Addr string

    Handler Handler // handler to invoke, http.DefaultServeMux if nil

    // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
    // otherwise responds with 200 OK and Content-Length: 0.
    DisableGeneralOptionsHandler bool // Go 1.20

    // TLSConfig optionally provides a TLS configuration for use
    // by ServeTLS and ListenAndServeTLS. Note that this value is
    // cloned by ServeTLS and ListenAndServeTLS, so it's not
    // possible to modify the configuration with methods like
    // tls.Config.SetSessionTicketKeys. To use
    // SetSessionTicketKeys, use Server.Serve with a TLS Listener
    // instead.
    TLSConfig *tls.Config

    // ReadTimeout is the maximum duration for reading the entire
    // request, including the body. A zero or negative value means
    // there will be no timeout.
    //
    // Because ReadTimeout does not let Handlers make per-request
    // decisions on each request body's acceptable deadline or
    // upload rate, most users will prefer to use
    // ReadHeaderTimeout. It is valid to use them both.
    ReadTimeout time.Duration

    // ReadHeaderTimeout is the amount of time allowed to read
    // request headers. The connection's read deadline is reset
    // after reading the headers and the Handler can decide what
    // is considered too slow for the body. If ReadHeaderTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    ReadHeaderTimeout time.Duration // Go 1.8

    // WriteTimeout is the maximum duration before timing out
    // writes of the response. It is reset whenever a new
    // request's header is read. Like ReadTimeout, it does not
    // let Handlers make decisions on a per-request basis.
    // A zero or negative value means there will be no timeout.
    WriteTimeout time.Duration

    // IdleTimeout is the maximum amount of time to wait for the
    // next request when keep-alives are enabled. If IdleTimeout
    // is zero, the value of ReadTimeout is used. If both are
    // zero, there is no timeout.
    IdleTimeout time.Duration // Go 1.8

    // MaxHeaderBytes controls the maximum number of bytes the
    // server will read parsing the request header's keys and
    // values, including the request line. It does not limit the
    // size of the request body.
    // If zero, DefaultMaxHeaderBytes is used.
    MaxHeaderBytes int

    // TLSNextProto optionally specifies a function to take over
    // ownership of the provided TLS connection when an ALPN
    // protocol upgrade has occurred. The map key is the protocol
    // name negotiated. The Handler argument should be used to
    // handle HTTP requests and will initialize the Request's TLS
    // and RemoteAddr if not already set. The connection is
    // automatically closed when the function returns.
    // If TLSNextProto is not nil, HTTP/2 support is not enabled
    // automatically.
    TLSNextProto map[string]func(*Server, *tls.Conn, Handler) // Go 1.1

    // ConnState specifies an optional callback function that is
    // called when a client connection changes state. See the
    // ConnState type and associated constants for details.
    ConnState func(net.Conn, ConnState) // Go 1.3

    // ErrorLog specifies an optional logger for errors accepting
    // connections, unexpected behavior from handlers, and
    // underlying FileSystem errors.
    // If nil, logging is done via the log package's standard logger.
    ErrorLog *log.Logger // Go 1.3

    // BaseContext optionally specifies a function that returns
    // the base context for incoming requests on this server.
    // The provided Listener is the specific Listener that's
    // about to start accepting requests.
    // If BaseContext is nil, the default is context.Background().
    // If non-nil, it must return a non-nil context.
    BaseContext func(net.Listener) context.Context // Go 1.13

    // ConnContext optionally specifies a function that modifies
    // the context used for a new connection c. The provided ctx
    // is derived from the base context and has a ServerContextKey
    // value.
    ConnContext func(ctx context.Context, c net.Conn) context.Context // Go 1.13
    // contains filtered or unexported fields
}
</pre> <h3 id="Server.Close">func (*Server) <span>Close</span>  <span title="Added in Go 1.8">1.8</span> </h3> <pre data-language="go">func (srv *Server) Close() error</pre> <p>Close immediately closes all active net.Listeners and any connections in state <a href="#StateNew">StateNew</a>, <a href="#StateActive">StateActive</a>, or <a href="#StateIdle">StateIdle</a>. For a graceful shutdown, use <a href="#Server.Shutdown">Server.Shutdown</a>. </p>
<p>Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets. </p>
<p>Close returns any error returned from closing the <a href="#Server">Server</a>'s underlying Listener(s). </p>
<h3 id="Server.ListenAndServe">func (*Server) <span>ListenAndServe</span>  </h3> <pre data-language="go">func (srv *Server) ListenAndServe() error</pre> <p>ListenAndServe listens on the TCP network address srv.Addr and then calls <a href="#Serve">Serve</a> to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives. </p>
<p>If srv.Addr is blank, ":http" is used. </p>
<p>ListenAndServe always returns a non-nil error. After <a href="#Server.Shutdown">Server.Shutdown</a> or <a href="#Server.Close">Server.Close</a>, the returned error is <a href="#ErrServerClosed">ErrServerClosed</a>. </p>
<h3 id="Server.ListenAndServeTLS">func (*Server) <span>ListenAndServeTLS</span>  </h3> <pre data-language="go">func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error</pre> <p>ListenAndServeTLS listens on the TCP network address srv.Addr and then calls <a href="#ServeTLS">ServeTLS</a> to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives. </p>
<p>Filenames containing a certificate and matching private key for the server must be provided if neither the <a href="#Server">Server</a>'s TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate. </p>
<p>If srv.Addr is blank, ":https" is used. </p>
<p>ListenAndServeTLS always returns a non-nil error. After <a href="#Server.Shutdown">Server.Shutdown</a> or <a href="#Server.Close">Server.Close</a>, the returned error is <a href="#ErrServerClosed">ErrServerClosed</a>. </p>
<h3 id="Server.RegisterOnShutdown">func (*Server) <span>RegisterOnShutdown</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (srv *Server) RegisterOnShutdown(f func())</pre> <p>RegisterOnShutdown registers a function to call on <a href="#Server.Shutdown">Server.Shutdown</a>. This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete. </p>
<h3 id="Server.Serve">func (*Server) <span>Serve</span>  </h3> <pre data-language="go">func (srv *Server) Serve(l net.Listener) error</pre> <p>Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them. </p>
<p>HTTP/2 support is only enabled if the Listener returns <span>*tls.Conn</span> connections and they were configured with "h2" in the TLS Config.NextProtos. </p>
<p>Serve always returns a non-nil error and closes l. After <a href="#Server.Shutdown">Server.Shutdown</a> or <a href="#Server.Close">Server.Close</a>, the returned error is <a href="#ErrServerClosed">ErrServerClosed</a>. </p>
<h3 id="Server.ServeTLS">func (*Server) <span>ServeTLS</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error</pre> <p>ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling srv.Handler to reply to them. </p>
<p>Files containing a certificate and matching private key for the server must be provided if neither the <a href="#Server">Server</a>'s TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate. </p>
<p>ServeTLS always returns a non-nil error. After <a href="#Server.Shutdown">Server.Shutdown</a> or <a href="#Server.Close">Server.Close</a>, the returned error is <a href="#ErrServerClosed">ErrServerClosed</a>. </p>
<h3 id="Server.SetKeepAlivesEnabled">func (*Server) <span>SetKeepAlivesEnabled</span>  <span title="Added in Go 1.3">1.3</span> </h3> <pre data-language="go">func (srv *Server) SetKeepAlivesEnabled(v bool)</pre> <p>SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments or servers in the process of shutting down should disable them. </p>
<h3 id="Server.Shutdown">func (*Server) <span>Shutdown</span>  <span title="Added in Go 1.8">1.8</span> </h3> <pre data-language="go">func (srv *Server) Shutdown(ctx context.Context) error</pre> <p>Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the <a href="#Server">Server</a>'s underlying Listener(s). </p>
<p>When Shutdown is called, <a href="#Serve">Serve</a>, <a href="#ListenAndServe">ListenAndServe</a>, and <a href="#ListenAndServeTLS">ListenAndServeTLS</a> immediately return <a href="#ErrServerClosed">ErrServerClosed</a>. Make sure the program doesn't exit and waits instead for Shutdown to return. </p>
<p>Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See <a href="#Server.RegisterOnShutdown">Server.RegisterOnShutdown</a> for a way to register shutdown notification functions. </p>
<p>Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed. </p>   <h4 id="example_Server_Shutdown"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
var srv http.Server

idleConnsClosed := make(chan struct{})
go func() {
    sigint := make(chan os.Signal, 1)
    signal.Notify(sigint, os.Interrupt)
    &lt;-sigint

    // We received an interrupt signal, shut down.
    if err := srv.Shutdown(context.Background()); err != nil {
        // Error from closing listeners, or context timeout:
        log.Printf("HTTP server Shutdown: %v", err)
    }
    close(idleConnsClosed)
}()

if err := srv.ListenAndServe(); err != http.ErrServerClosed {
    // Error starting or closing listener:
    log.Fatalf("HTTP server ListenAndServe: %v", err)
}

&lt;-idleConnsClosed
</pre>   <h2 id="Transport">type <span>Transport</span>  </h2> <p>Transport is an implementation of <a href="#RoundTripper">RoundTripper</a> that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT). </p>
<p>By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using <a href="#Transport.CloseIdleConnections">Transport.CloseIdleConnections</a> method and the [Transport.MaxIdleConnsPerHost] and [Transport.DisableKeepAlives] fields. </p>
<p>Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines. </p>
<p>A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see <a href="#Client">Client</a>. </p>
<p>Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The <a href="#DefaultTransport">DefaultTransport</a> supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2. </p>
<p>Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by <a href="#Transport.RoundTrip">Transport.RoundTrip</a>. To see the ignored 1xx responses, use the httptrace trace package's ClientTrace.Got1xxResponse. </p>
<p>Transport only retries a request upon encountering a network error if the connection has been already been used successfully and if the request is idempotent and either has no body or has its [Request.GetBody] defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their <a href="#Header">Header</a> map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire. </p>
<pre data-language="go">type Transport struct {

    // Proxy specifies a function to return a proxy for a given
    // Request. If the function returns a non-nil error, the
    // request is aborted with the provided error.
    //
    // The proxy type is determined by the URL scheme. "http",
    // "https", and "socks5" are supported. If the scheme is empty,
    // "http" is assumed.
    //
    // If the proxy URL contains a userinfo subcomponent,
    // the proxy request will pass the username and password
    // in a Proxy-Authorization header.
    //
    // If Proxy is nil or returns a nil *URL, no proxy is used.
    Proxy func(*Request) (*url.URL, error)

    // OnProxyConnectResponse is called when the Transport gets an HTTP response from
    // a proxy for a CONNECT request. It's called before the check for a 200 OK response.
    // If it returns an error, the request fails with that error.
    OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error // Go 1.20

    // DialContext specifies the dial function for creating unencrypted TCP connections.
    // If DialContext is nil (and the deprecated Dial below is also nil),
    // then the transport dials using package net.
    //
    // DialContext runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later DialContext completes.
    DialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.7

    // Dial specifies the dial function for creating unencrypted TCP connections.
    //
    // Dial runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later Dial completes.
    //
    // Deprecated: Use DialContext instead, which allows the transport
    // to cancel dials as soon as they are no longer needed.
    // If both are set, DialContext takes priority.
    Dial func(network, addr string) (net.Conn, error)

    // DialTLSContext specifies an optional dial function for creating
    // TLS connections for non-proxied HTTPS requests.
    //
    // If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
    // DialContext and TLSClientConfig are used.
    //
    // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
    // requests and the TLSClientConfig and TLSHandshakeTimeout
    // are ignored. The returned net.Conn is assumed to already be
    // past the TLS handshake.
    DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.14

    // DialTLS specifies an optional dial function for creating
    // TLS connections for non-proxied HTTPS requests.
    //
    // Deprecated: Use DialTLSContext instead, which allows the transport
    // to cancel dials as soon as they are no longer needed.
    // If both are set, DialTLSContext takes priority.
    DialTLS func(network, addr string) (net.Conn, error) // Go 1.4

    // TLSClientConfig specifies the TLS configuration to use with
    // tls.Client.
    // If nil, the default configuration is used.
    // If non-nil, HTTP/2 support may not be enabled by default.
    TLSClientConfig *tls.Config

    // TLSHandshakeTimeout specifies the maximum amount of time to
    // wait for a TLS handshake. Zero means no timeout.
    TLSHandshakeTimeout time.Duration // Go 1.3

    // DisableKeepAlives, if true, disables HTTP keep-alives and
    // will only use the connection to the server for a single
    // HTTP request.
    //
    // This is unrelated to the similarly named TCP keep-alives.
    DisableKeepAlives bool

    // DisableCompression, if true, prevents the Transport from
    // requesting compression with an "Accept-Encoding: gzip"
    // request header when the Request contains no existing
    // Accept-Encoding value. If the Transport requests gzip on
    // its own and gets a gzipped response, it's transparently
    // decoded in the Response.Body. However, if the user
    // explicitly requested gzip it is not automatically
    // uncompressed.
    DisableCompression bool

    // MaxIdleConns controls the maximum number of idle (keep-alive)
    // connections across all hosts. Zero means no limit.
    MaxIdleConns int // Go 1.7

    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
    // (keep-alive) connections to keep per-host. If zero,
    // DefaultMaxIdleConnsPerHost is used.
    MaxIdleConnsPerHost int

    // MaxConnsPerHost optionally limits the total number of
    // connections per host, including connections in the dialing,
    // active, and idle states. On limit violation, dials will block.
    //
    // Zero means no limit.
    MaxConnsPerHost int // Go 1.11

    // IdleConnTimeout is the maximum amount of time an idle
    // (keep-alive) connection will remain idle before closing
    // itself.
    // Zero means no limit.
    IdleConnTimeout time.Duration // Go 1.7

    // ResponseHeaderTimeout, if non-zero, specifies the amount of
    // time to wait for a server's response headers after fully
    // writing the request (including its body, if any). This
    // time does not include the time to read the response body.
    ResponseHeaderTimeout time.Duration // Go 1.1

    // ExpectContinueTimeout, if non-zero, specifies the amount of
    // time to wait for a server's first response headers after fully
    // writing the request headers if the request has an
    // "Expect: 100-continue" header. Zero means no timeout and
    // causes the body to be sent immediately, without
    // waiting for the server to approve.
    // This time does not include the time to send the request header.
    ExpectContinueTimeout time.Duration // Go 1.6

    // TLSNextProto specifies how the Transport switches to an
    // alternate protocol (such as HTTP/2) after a TLS ALPN
    // protocol negotiation. If Transport dials a TLS connection
    // with a non-empty protocol name and TLSNextProto contains a
    // map entry for that key (such as "h2"), then the func is
    // called with the request's authority (such as "example.com"
    // or "example.com:1234") and the TLS connection. The function
    // must return a RoundTripper that then handles the request.
    // If TLSNextProto is not nil, HTTP/2 support is not enabled
    // automatically.
    TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper // Go 1.6

    // ProxyConnectHeader optionally specifies headers to send to
    // proxies during CONNECT requests.
    // To set the header dynamically, see GetProxyConnectHeader.
    ProxyConnectHeader Header // Go 1.8

    // GetProxyConnectHeader optionally specifies a func to return
    // headers to send to proxyURL during a CONNECT request to the
    // ip:port target.
    // If it returns an error, the Transport's RoundTrip fails with
    // that error. It can return (nil, nil) to not add headers.
    // If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
    // ignored.
    GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error) // Go 1.16

    // MaxResponseHeaderBytes specifies a limit on how many
    // response bytes are allowed in the server's response
    // header.
    //
    // Zero means to use a default limit.
    MaxResponseHeaderBytes int64 // Go 1.7

    // WriteBufferSize specifies the size of the write buffer used
    // when writing to the transport.
    // If zero, a default (currently 4KB) is used.
    WriteBufferSize int // Go 1.13

    // ReadBufferSize specifies the size of the read buffer used
    // when reading from the transport.
    // If zero, a default (currently 4KB) is used.
    ReadBufferSize int // Go 1.13

    // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
    // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
    // By default, use of any those fields conservatively disables HTTP/2.
    // To use a custom dialer or TLS config and still attempt HTTP/2
    // upgrades, set this to true.
    ForceAttemptHTTP2 bool // Go 1.13
    // contains filtered or unexported fields
}
</pre> <h3 id="Transport.CancelRequest">func (*Transport) <span>CancelRequest</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (t *Transport) CancelRequest(req *Request)</pre> <p>CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after <a href="#Transport.RoundTrip">Transport.RoundTrip</a> has returned. </p>
<p>Deprecated: Use <a href="#Request.WithContext">Request.WithContext</a> to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests. </p>
<h3 id="Transport.Clone">func (*Transport) <span>Clone</span>  <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func (t *Transport) Clone() *Transport</pre> <p>Clone returns a deep copy of t's exported fields. </p>
<h3 id="Transport.CloseIdleConnections">func (*Transport) <span>CloseIdleConnections</span>  </h3> <pre data-language="go">func (t *Transport) CloseIdleConnections()</pre> <p>CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use. </p>
<h3 id="Transport.RegisterProtocol">func (*Transport) <span>RegisterProtocol</span>  </h3> <pre data-language="go">func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)</pre> <p>RegisterProtocol registers a new protocol with scheme. The <a href="#Transport">Transport</a> will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics. </p>
<p>RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file". </p>
<p>If rt.RoundTrip returns <a href="#ErrSkipAltProtocol">ErrSkipAltProtocol</a>, the Transport will handle the <a href="#Transport.RoundTrip">Transport.RoundTrip</a> itself for that one request, as if the protocol were not registered. </p>
<h3 id="Transport.RoundTrip">func (*Transport) <span>RoundTrip</span>  </h3> <pre data-language="go">func (t *Transport) RoundTrip(req *Request) (*Response, error)</pre> <p>RoundTrip implements the <a href="#RoundTripper">RoundTripper</a> interface. </p>
<p>For higher-level HTTP client support (such as handling of cookies and redirects), see <a href="#Get">Get</a>, <a href="#Post">Post</a>, and the <a href="#Client">Client</a> type. </p>
<p>Like the RoundTripper interface, the error types returned by RoundTrip are unspecified. </p>
<h2 id="pkg-subdirectories">Subdirectories</h2> <div class="pkg-dir"> <table> <tr> <th class="pkg-name">Name</th> <th class="pkg-synopsis">Synopsis</th> </tr> <tr> <td colspan="2"><a href="../index">..</a></td> </tr> <tr> <td class="pkg-name"> <a href="cgi/index">cgi</a> </td> <td class="pkg-synopsis"> Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875. </td> </tr> <tr> <td class="pkg-name"> <a href="cookiejar/index">cookiejar</a> </td> <td class="pkg-synopsis"> Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. </td> </tr> <tr> <td class="pkg-name"> <a href="fcgi/index">fcgi</a> </td> <td class="pkg-synopsis"> Package fcgi implements the FastCGI protocol. </td> </tr> <tr> <td class="pkg-name"> <a href="httptest/index">httptest</a> </td> <td class="pkg-synopsis"> Package httptest provides utilities for HTTP testing. </td> </tr> <tr> <td class="pkg-name"> <a href="httptrace/index">httptrace</a> </td> <td class="pkg-synopsis"> Package httptrace provides mechanisms to trace the events within HTTP client requests. </td> </tr> <tr> <td class="pkg-name"> <a href="httputil/index">httputil</a> </td> <td class="pkg-synopsis"> Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package. </td> </tr> <tr> <td class="pkg-name"> <a href="pprof/index">pprof</a> </td> <td class="pkg-synopsis"> Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. </td> </tr> </table> </div><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/net/http/" class="_attribution-link">http://golang.org/pkg/net/http/</a>
  </p>
</div>