The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/encoding/binary.littleEndian^40d0b.html b/imp/encoding/binary.littleEndian^40d0b.html
index 567c44308a4..7bacb72ddee 100644
--- a/imp/encoding/binary.littleEndian^40d0b.html
+++ b/imp/encoding/binary.littleEndian^40d0b.html
@@ -36,12 +36,12 @@
littleEndian.M : ByteOrder.Uint16
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/encoding/binary.nativeEndian^61760.html b/imp/encoding/binary.nativeEndian^61760.html
index 898ffc34aec..1d82ea80fc1 100644
--- a/imp/encoding/binary.nativeEndian^61760.html
+++ b/imp/encoding/binary.nativeEndian^61760.html
@@ -36,12 +36,12 @@
nativeEndian.M : ByteOrder.Uint16
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/golang.org/x/sys/cpu.byteOrder^5f5cc.html b/imp/golang.org/x/sys/cpu.byteOrder^5f5cc.html
index 72221711316..31c784190dc 100644
--- a/imp/golang.org/x/sys/cpu.byteOrder^5f5cc.html
+++ b/imp/golang.org/x/sys/cpu.byteOrder^5f5cc.html
@@ -20,7 +20,7 @@
encoding/binary.littleEndian.Uint32
encoding/binary.nativeEndian.littleEndian.Uint32
vendor/golang.org/x/sys/cpu.bigEndian.Uint32
- vendor/golang.org/x/sys/cpu.byteOrder.Uint32
+ vendor/golang.org/x/sys/cpu.byteOrder.Uint32
vendor/golang.org/x/sys/cpu.littleEndian.Uint32
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/net/http.ConnState.html b/imp/net/http.ConnState.html
index a48b73ae15e..0a6cb7e2009 100644
--- a/imp/net/http.ConnState.html
+++ b/imp/net/http.ConnState.html
@@ -8,7 +8,7 @@
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/net/http.Pusher.html b/imp/net/http.Pusher.html
index 335215a4f7b..92aaab91ed4 100644
--- a/imp/net/http.Pusher.html
+++ b/imp/net/http.Pusher.html
@@ -14,7 +14,7 @@
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/net/http.ServeMux.html b/imp/net/http.ServeMux.html
index d0f0c4b59c5..93c79b7cc60 100644
--- a/imp/net/http.ServeMux.html
+++ b/imp/net/http.ServeMux.html
@@ -8,7 +8,7 @@
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/imp/vendor/golang.org/x/sys/cpu.byteOrder^5f5cc.html b/imp/vendor/golang.org/x/sys/cpu.byteOrder^5f5cc.html
index db9296b6b09..9e31a5fcf2f 100644
--- a/imp/vendor/golang.org/x/sys/cpu.byteOrder^5f5cc.html
+++ b/imp/vendor/golang.org/x/sys/cpu.byteOrder^5f5cc.html
@@ -20,7 +20,7 @@
encoding/binary.littleEndian.Uint32
encoding/binary.nativeEndian.littleEndian.Uint32
golang.org/x/sys/cpu.bigEndian.Uint32
- golang.org/x/sys/cpu.byteOrder.Uint32
+ golang.org/x/sys/cpu.byteOrder.Uint32
golang.org/x/sys/cpu.littleEndian.Uint32
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
diff --git a/index.html b/index.html
index b8b02834720..3c201510a05 100644
--- a/index.html
+++ b/index.html
@@ -13,7 +13,7 @@
Statistics (detailed ones)
Total 306 packages analyzed and 4810 Go files
- (1595771 lines of code) parsed. On average,
+ (1595773 lines of code) parsed. On average,
* each Go source file imports 7.18 packages
and contains 332 lines of code.
* each package depends on 6.70 other packages,
@@ -22,7 +22,7 @@
- 4.29 variables,
- 27.30 constants,
- 13.51 functions.
-
All Packages (sort packages by: | | | )
3
1. bufio (14) (1269) (10) (4) - implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
9. context (31) (806) (11) (2) - defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
11. crypto/aes (10) (48) (19) (3) - implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
3
12. crypto/cipher (17) (1040) (17) (3) - implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
3
13. crypto/des (3) (556) (18) (4) - implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
3
14. crypto/dsa (1) (330) (20) (4) - implements the Digital Signature Algorithm, as defined in FIPS 186-3.
3
15. crypto/ecdh (6) (551) (20) (4) - implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
3
16. crypto/ecdsa (3) (868) (21) (4) - implements the Elliptic Curve Digital Signature Algorithm, as defined in [FIPS 186-5].
18. crypto/elliptic (4) (884) (16) (4) - implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
3
19. crypto/fips140 (6) (93) (14) (4) - provides information about the FIPS 140-3 Go Cryptographic Module and FIPS 140-3 mode.
3
20. crypto/hkdf (4) (84) (17) (5) - implements the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869.
3
21. crypto/hmac (5) (65) (19) (5) - implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
3
22. crypto/hpke (1) (1482) (21) (5) - implements Hybrid Public Key Encryption (HPKE) as defined in [RFC 9180].
25. crypto/internal/boring/sig (1) (17) (1) (4) - holds “code signatures” that can be called and will result in certain code sequences being linked into the final binary.
42. crypto/internal/fips140/mlkem (1) (1573) (16) (6) - implements the quantum-resistant key encapsulation method ML-KEM (formerly known as Kyber), as specified in [NIST FIPS 203].
47. crypto/internal/fips140/sha256 (9) (440) (11) (4) - implements the SHA-224 and SHA-256 hash algorithms as defined in FIPS 180-4.
3
48. crypto/internal/fips140/sha3 (6) (933) (11) (4) - implements the SHA-3 fixed-output-length hash functions and the SHAKE variable-output-length functions defined by [FIPS 202], as well as the cSHAKE extendable-output-length functions defined by [SP 800-185].
3
49. crypto/internal/fips140/sha512 (7) (515) (11) (4) - implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
52. crypto/internal/fips140/tls13 (1) (215) (15) (5) - implements the TLS 1.3 Key Schedule as specified in RFC 8446, Section 7.1 and allowed by FIPS 140-3 IG 2.4.B Resolution 7.
3
53. crypto/internal/fips140cache (2) (52) (7) (5) - provides a weak map that associates the lifetime of values with the lifetime of keys.
60. crypto/internal/impl (6) (107) (10) (4) - is a registry of alternative implementations of cryptographic primitives, to allow selecting them for testing.
62. crypto/internal/randutil (1) (26) (9) (4) - contains internal randomness utilities for various crypto packages.
3
63. crypto/internal/sysrand (1) (144) (14) (5) - rand provides cryptographically secure random bytes from the operating system.
3
64. crypto/md5 (4) (347) (17) (4) - implements the MD5 hash algorithm as defined in RFC 1321.
3
65. crypto/mlkem (3) (221) (17) (5) - implements the quantum-resistant key encapsulation method ML-KEM (formerly known as Kyber), as specified in [NIST FIPS 203].
3
66. crypto/pbkdf2 (1) (54) (17) (5) - implements the key derivation function PBKDF2 as defined in RFC 8018 (PKCS #5 v2.1).
3
67. crypto/rand (11) (198) (20) (3) - implements a cryptographically secure random number generator.
3
68. crypto/rc4 (2) (83) (17) (5) - implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.
3
69. crypto/rsa (7) (1441) (21) (2) - implements RSA encryption as specified in PKCS #1 and RFC 8017.
3
70. crypto/sha1 (6) (413) (19) (3) - implements the SHA-1 hash algorithm as defined in RFC 3174.
3
71. crypto/sha256 (8) (74) (19) (3) - implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
3
72. crypto/sha3 (3) (274) (12) (4) - implements the SHA-3 hash algorithms and the SHAKE extendable output functions defined in FIPS 202.
3
73. crypto/sha512 (7) (123) (19) (4) - implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
3
74. crypto/subtle (11) (134) (4) (3) - implements functions that are often useful in cryptographic code but require careful thought to use correctly.
3
75. crypto/tls (2) (14431) (23) (4) - partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
77. crypto/x509 (3) (7768) (22) (3) - implements a subset of the X.509 standard.
3
78. crypto/x509/pkix (1) (320) (17) (4) - contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
3
79. embed (1) (436) (12) (3) - provides access to files embedded in the running Go program.
3
80. encoding (1) (78) (1) (4) - defines interfaces shared by other packages that convert data to and from byte-level and textual representations.
3
81. encoding/asn1 (4) (2116) (16) (4) - implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
3
82. encoding/base64 (14) (665) (9) (3) - implements base64 encoding as specified by RFC 4648.
3
83. encoding/binary (33) (1214) (10) (3) - implements simple translation between numbers and byte sequences and encoding and decoding of varints.
93. github.com/cespare/xxhash/v2 (1) (316) (11) (3) - implements the 64-bit variant of xxHash (XXH64) as described at http://cyan4973.github.io/xxHash/.
103. github.com/gotd/log (8) (460) (15) (1) - defines a minimal, dependency-free logging port for gotd libraries.
3
104. github.com/gotd/neo (1) (538) (15) (2) - implements side effects simulation for testing.
3
105. github.com/gotd/td/ascii (1) (19) (1) (2) - provides data and functions to test some properties of ASCII code points.
3
106. github.com/gotd/td/bin (17) (742) (16) (1) - implements binary serialization and deserialization for TL, providing Buffer that can decode and encode basic Type Language types.
146. github.com/klauspost/compress/gzip (1) (670) (17) (2) - implements reading and writing of gzip format compressed files, as specified in RFC 1952.
3
147. github.com/klauspost/compress/huff0 (1) (2956) (16) (6) - This file contains the specialisation of Decoder.Decompress4X and Decoder.Decompress1X that use an asm implementation of thir main loops.
153. github.com/refraction-networking/utls (1) (25388) (28) (4) - partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
180. go.uber.org/atomic (3) (1716) (16) (1) - provides simple wrappers around numerics to enforce atomic access.
3
181. go.uber.org/multierr (9) (694) (15) (1) - allows combining one or more errors together.
3
182. golang.org/x/crypto/chacha20 (1) (453) (18) (6) - implements the ChaCha20 and XChaCha20 encryption algorithms as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
183. golang.org/x/crypto/chacha20poly1305 (2) (380) (19) (5) - implements the ChaCha20-Poly1305 AEAD and its extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
184. golang.org/x/crypto/cryptobyte (2) (1358) (17) (5) - contains types that help with parsing and constructing length-prefixed, binary messages, including ASN.1 DER.
3
185. golang.org/x/crypto/cryptobyte/asn1 (1) (46) (1) (6) - contains supporting types for parsing and building ASN.1 messages with the cryptobyte package.
3
186. golang.org/x/crypto/hkdf (1) (100) (20) (5) - implements the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869.
192. golang.org/x/net/proxy (1) (429) (16) (1) - provides support for a variety of protocols to proxy network data.
3
193. golang.org/x/sync/errgroup (1) (151) (15) (2) - provides synchronization, error propagation, and Context cancellation for groups of goroutines working on subtasks of a common task.
212. internal/godebug (13) (316) (8) (3) - makes the settings in the $GODEBUG environment variable available to other packages.
3
213. internal/godebugs (2) (115) (1) (4) - provides a table of known GODEBUG settings, for use by a variety of other packages, including internal/godebug, runtime, runtime/metrics, and cmd/go/internal/load.
3
214. internal/goexperiment (1) (291) (1) (4) - implements support for toolchain experiments.
216. internal/msan (2) (37) (2) (4) - contains helper functions for manually instrumenting code for the memory sanitizer.
3
217. internal/nettrace (2) (46) (1) (4) - contains internal hooks for tracing activity in the net package.
3
218. internal/oserror (2) (18) (8) (4) - defines errors values used in the os package.
3
219. internal/poll (3) (2390) (11) (3) - supports non-blocking I/O on file descriptors with polling.
3
220. internal/profilerecord (1) (28) (1) (4) - holds internal types used to represent profiling records with deep stack traces.
3
221. internal/race (6) (66) (3) (3) - contains helper functions for manually instrumenting code for the race detector.
3
222. internal/reflectlite (3) (1201) (6) (3) - implements lightweight version of reflect, not using any package except for "runtime", "unsafe", and "internal/abi"
3
223. internal/runtime/atomic (2) (876) (2) (4) - provides atomic operations, independent of sync/atomic, to the runtime.
236. internal/stringslite (10) (150) (4) (3) - implements a subset of strings, only using packages that may be imported by "os".
3
237. internal/sync (2) (1010) (4) (3) - provides basic synchronization primitives such as mutual exclusion locks to internal packages (including ones that depend on sync).
3
238. internal/synctest (1) (105) (3) (3) - provides support for testing concurrent code.
241. internal/testlog (1) (113) (7) (3) - provides a back-channel communication path between tests and package os, so that cmd/go can see which environment variables and files a test consults.
3
242. internal/trace/tracev2 (1) (707) (1) (4) - contains definitions for the v2 execution trace wire format.
3
243. internal/unsafeheader (2) (37) (2) (4) - contains header declarations for the Go runtime's slice and string implementations.
252. math/bits (49) (693) (2) (2) - implements bit counting and manipulation functions for the predeclared unsigned integer types.
3
253. math/rand (4) (1265) (9) (3) - implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
3
254. math/rand/v2 (2) (1046) (8) (5) - implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
3
255. mime (2) (1295) (15) (4) - implements parts of the MIME spec.
3
256. mime/multipart (1) (1023) (21) (4) - implements MIME multipart parsing, as defined in RFC 2046.
3
257. mime/quotedprintable (1) (312) (15) (5) - implements quoted-printable encoding as specified by RFC 2045.
3
258. net (19) (12982) (14) (3) - provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
3
259. net/http (4) (29489) (26) (3) - provides HTTP client and server implementations.
3
260. net/http/httptrace (2) (255) (24) (4) - provides mechanisms to trace the events within HTTP client requests.
3
261. net/http/internal (1) (300) (15) (4) - contains HTTP internals shared by net/http and net/http/httputil.
269. path/filepath (5) (1039) (14) (2) - implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
3
270. reflect (15) (8694) (9) (3) - implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
3
271. rsc.io/qr (1) (516) (16) (2) - encodes QR codes.
283. syscall (9) (8451) (9) (3) - contains an interface to the low-level operating system primitives.
3
284. time (46) (5623) (10) (2) - provides functionality for measuring and displaying time.
3
285. unicode (8) (10330) (1) (3) - provides data and functions to test some properties of Unicode code points.
3
286. unicode/utf16 (4) (144) (1) (3) - implements encoding and decoding of UTF-16 sequences.
3
287. unicode/utf8 (25) (578) (1) (3) - implements functions and constants to support text encoded in UTF-8.
3
288. unique (1) (552) (7) (4) - The unique package provides facilities for canonicalizing ("interning") comparable values.
3
289. unsafe (81) (271) (1) (3) - contains operations that step around the type safety of Go programs.
3
290. vendor/golang.org/x/crypto/chacha20 (1) (453) (18) (6) - implements the ChaCha20 and XChaCha20 encryption algorithms as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
291. vendor/golang.org/x/crypto/chacha20poly1305 (2) (380) (19) (5) - implements the ChaCha20-Poly1305 AEAD and its extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
292. vendor/golang.org/x/crypto/cryptobyte (3) (1358) (17) (4) - contains types that help with parsing and constructing length-prefixed, binary messages, including ASN.1 DER.
298. vendor/golang.org/x/net/http/httpproxy (1) (373) (19) (4) - provides support for HTTP proxy determination based on environment variables, as provided by net/http's ProxyFromEnvironment function.
3
299. vendor/golang.org/x/net/http2/hpack (2) (1585) (15) (4) - implements HPACK, a compression format for efficiently representing HTTP header fields in the context of HTTP/2.
3
300. vendor/golang.org/x/net/idna (3) (6354) (18) (4) - implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
3
301. vendor/golang.org/x/sys/cpu (1) (759) (14) (6) - implements processor feature detection for various CPU architectures.
303. vendor/golang.org/x/text/transform (2) (709) (10) (6) - provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
306. weak (4) (107) (6) (5) - provides ways to safely reference memory weakly, that is, without preventing its reclamation.
+
All Packages (sort packages by: | | | )
3
1. bufio (14) (1269) (10) (4) - implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
9. context (31) (806) (11) (2) - defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
11. crypto/aes (10) (48) (19) (3) - implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
3
12. crypto/cipher (17) (1040) (17) (3) - implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
3
13. crypto/des (3) (556) (18) (4) - implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
3
14. crypto/dsa (1) (330) (20) (4) - implements the Digital Signature Algorithm, as defined in FIPS 186-3.
3
15. crypto/ecdh (6) (551) (20) (4) - implements Elliptic Curve Diffie-Hellman over NIST curves and Curve25519.
3
16. crypto/ecdsa (3) (868) (21) (4) - implements the Elliptic Curve Digital Signature Algorithm, as defined in [FIPS 186-5].
18. crypto/elliptic (4) (884) (16) (4) - implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
3
19. crypto/fips140 (6) (93) (14) (4) - provides information about the FIPS 140-3 Go Cryptographic Module and FIPS 140-3 mode.
3
20. crypto/hkdf (4) (84) (17) (5) - implements the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869.
3
21. crypto/hmac (5) (65) (19) (5) - implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
3
22. crypto/hpke (1) (1482) (21) (5) - implements Hybrid Public Key Encryption (HPKE) as defined in [RFC 9180].
25. crypto/internal/boring/sig (1) (17) (1) (4) - holds “code signatures” that can be called and will result in certain code sequences being linked into the final binary.
42. crypto/internal/fips140/mlkem (1) (1573) (16) (6) - implements the quantum-resistant key encapsulation method ML-KEM (formerly known as Kyber), as specified in [NIST FIPS 203].
47. crypto/internal/fips140/sha256 (9) (440) (11) (4) - implements the SHA-224 and SHA-256 hash algorithms as defined in FIPS 180-4.
3
48. crypto/internal/fips140/sha3 (6) (933) (11) (4) - implements the SHA-3 fixed-output-length hash functions and the SHAKE variable-output-length functions defined by [FIPS 202], as well as the cSHAKE extendable-output-length functions defined by [SP 800-185].
3
49. crypto/internal/fips140/sha512 (7) (515) (11) (4) - implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
52. crypto/internal/fips140/tls13 (1) (215) (15) (5) - implements the TLS 1.3 Key Schedule as specified in RFC 8446, Section 7.1 and allowed by FIPS 140-3 IG 2.4.B Resolution 7.
3
53. crypto/internal/fips140cache (2) (52) (7) (5) - provides a weak map that associates the lifetime of values with the lifetime of keys.
60. crypto/internal/impl (6) (107) (10) (4) - is a registry of alternative implementations of cryptographic primitives, to allow selecting them for testing.
62. crypto/internal/randutil (1) (26) (9) (4) - contains internal randomness utilities for various crypto packages.
3
63. crypto/internal/sysrand (1) (144) (14) (5) - rand provides cryptographically secure random bytes from the operating system.
3
64. crypto/md5 (4) (347) (17) (4) - implements the MD5 hash algorithm as defined in RFC 1321.
3
65. crypto/mlkem (3) (221) (17) (5) - implements the quantum-resistant key encapsulation method ML-KEM (formerly known as Kyber), as specified in [NIST FIPS 203].
3
66. crypto/pbkdf2 (1) (54) (17) (5) - implements the key derivation function PBKDF2 as defined in RFC 8018 (PKCS #5 v2.1).
3
67. crypto/rand (11) (198) (20) (3) - implements a cryptographically secure random number generator.
3
68. crypto/rc4 (2) (83) (17) (5) - implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography.
3
69. crypto/rsa (7) (1441) (21) (2) - implements RSA encryption as specified in PKCS #1 and RFC 8017.
3
70. crypto/sha1 (6) (413) (19) (3) - implements the SHA-1 hash algorithm as defined in RFC 3174.
3
71. crypto/sha256 (8) (74) (19) (3) - implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
3
72. crypto/sha3 (3) (274) (12) (4) - implements the SHA-3 hash algorithms and the SHAKE extendable output functions defined in FIPS 202.
3
73. crypto/sha512 (7) (123) (19) (4) - implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
3
74. crypto/subtle (11) (134) (4) (3) - implements functions that are often useful in cryptographic code but require careful thought to use correctly.
3
75. crypto/tls (2) (14431) (23) (4) - partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
77. crypto/x509 (3) (7768) (22) (3) - implements a subset of the X.509 standard.
3
78. crypto/x509/pkix (1) (320) (17) (4) - contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
3
79. embed (1) (436) (12) (3) - provides access to files embedded in the running Go program.
3
80. encoding (1) (78) (1) (4) - defines interfaces shared by other packages that convert data to and from byte-level and textual representations.
3
81. encoding/asn1 (4) (2116) (16) (4) - implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
3
82. encoding/base64 (14) (665) (9) (3) - implements base64 encoding as specified by RFC 4648.
3
83. encoding/binary (33) (1214) (10) (3) - implements simple translation between numbers and byte sequences and encoding and decoding of varints.
93. github.com/cespare/xxhash/v2 (1) (316) (11) (3) - implements the 64-bit variant of xxHash (XXH64) as described at http://cyan4973.github.io/xxHash/.
103. github.com/gotd/log (8) (460) (15) (1) - defines a minimal, dependency-free logging port for gotd libraries.
3
104. github.com/gotd/neo (1) (538) (15) (2) - implements side effects simulation for testing.
3
105. github.com/gotd/td/ascii (1) (19) (1) (2) - provides data and functions to test some properties of ASCII code points.
3
106. github.com/gotd/td/bin (17) (742) (16) (1) - implements binary serialization and deserialization for TL, providing Buffer that can decode and encode basic Type Language types.
146. github.com/klauspost/compress/gzip (1) (670) (17) (2) - implements reading and writing of gzip format compressed files, as specified in RFC 1952.
3
147. github.com/klauspost/compress/huff0 (1) (2956) (16) (6) - This file contains the specialisation of Decoder.Decompress4X and Decoder.Decompress1X that use an asm implementation of thir main loops.
153. github.com/refraction-networking/utls (1) (25388) (28) (4) - partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
180. go.uber.org/atomic (3) (1716) (16) (1) - provides simple wrappers around numerics to enforce atomic access.
3
181. go.uber.org/multierr (9) (694) (15) (1) - allows combining one or more errors together.
3
182. golang.org/x/crypto/chacha20 (1) (453) (18) (6) - implements the ChaCha20 and XChaCha20 encryption algorithms as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
183. golang.org/x/crypto/chacha20poly1305 (2) (380) (19) (5) - implements the ChaCha20-Poly1305 AEAD and its extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
184. golang.org/x/crypto/cryptobyte (2) (1358) (17) (5) - contains types that help with parsing and constructing length-prefixed, binary messages, including ASN.1 DER.
3
185. golang.org/x/crypto/cryptobyte/asn1 (1) (46) (1) (6) - contains supporting types for parsing and building ASN.1 messages with the cryptobyte package.
3
186. golang.org/x/crypto/hkdf (1) (100) (20) (5) - implements the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869.
192. golang.org/x/net/proxy (1) (429) (16) (1) - provides support for a variety of protocols to proxy network data.
3
193. golang.org/x/sync/errgroup (1) (151) (15) (2) - provides synchronization, error propagation, and Context cancellation for groups of goroutines working on subtasks of a common task.
212. internal/godebug (13) (316) (8) (3) - makes the settings in the $GODEBUG environment variable available to other packages.
3
213. internal/godebugs (2) (115) (1) (4) - provides a table of known GODEBUG settings, for use by a variety of other packages, including internal/godebug, runtime, runtime/metrics, and cmd/go/internal/load.
3
214. internal/goexperiment (1) (291) (1) (4) - implements support for toolchain experiments.
216. internal/msan (2) (37) (2) (4) - contains helper functions for manually instrumenting code for the memory sanitizer.
3
217. internal/nettrace (2) (46) (1) (4) - contains internal hooks for tracing activity in the net package.
3
218. internal/oserror (2) (18) (8) (4) - defines errors values used in the os package.
3
219. internal/poll (3) (2390) (11) (3) - supports non-blocking I/O on file descriptors with polling.
3
220. internal/profilerecord (1) (28) (1) (4) - holds internal types used to represent profiling records with deep stack traces.
3
221. internal/race (6) (66) (3) (3) - contains helper functions for manually instrumenting code for the race detector.
3
222. internal/reflectlite (3) (1201) (6) (3) - implements lightweight version of reflect, not using any package except for "runtime", "unsafe", and "internal/abi"
3
223. internal/runtime/atomic (2) (876) (2) (4) - provides atomic operations, independent of sync/atomic, to the runtime.
236. internal/stringslite (10) (150) (4) (3) - implements a subset of strings, only using packages that may be imported by "os".
3
237. internal/sync (2) (1010) (4) (3) - provides basic synchronization primitives such as mutual exclusion locks to internal packages (including ones that depend on sync).
3
238. internal/synctest (1) (105) (3) (3) - provides support for testing concurrent code.
241. internal/testlog (1) (113) (7) (3) - provides a back-channel communication path between tests and package os, so that cmd/go can see which environment variables and files a test consults.
3
242. internal/trace/tracev2 (1) (707) (1) (4) - contains definitions for the v2 execution trace wire format.
3
243. internal/unsafeheader (2) (37) (2) (4) - contains header declarations for the Go runtime's slice and string implementations.
252. math/bits (49) (693) (2) (2) - implements bit counting and manipulation functions for the predeclared unsigned integer types.
3
253. math/rand (4) (1265) (9) (3) - implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
3
254. math/rand/v2 (2) (1046) (8) (5) - implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work.
3
255. mime (2) (1295) (15) (4) - implements parts of the MIME spec.
3
256. mime/multipart (1) (1023) (21) (4) - implements MIME multipart parsing, as defined in RFC 2046.
3
257. mime/quotedprintable (1) (312) (15) (5) - implements quoted-printable encoding as specified by RFC 2045.
3
258. net (19) (12982) (14) (3) - provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
3
259. net/http (4) (29491) (26) (3) - provides HTTP client and server implementations.
3
260. net/http/httptrace (2) (255) (24) (4) - provides mechanisms to trace the events within HTTP client requests.
3
261. net/http/internal (1) (300) (15) (4) - contains HTTP internals shared by net/http and net/http/httputil.
269. path/filepath (5) (1039) (14) (2) - implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
3
270. reflect (15) (8694) (9) (3) - implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
3
271. rsc.io/qr (1) (516) (16) (2) - encodes QR codes.
283. syscall (9) (8451) (9) (3) - contains an interface to the low-level operating system primitives.
3
284. time (46) (5623) (10) (2) - provides functionality for measuring and displaying time.
3
285. unicode (8) (10330) (1) (3) - provides data and functions to test some properties of Unicode code points.
3
286. unicode/utf16 (4) (144) (1) (3) - implements encoding and decoding of UTF-16 sequences.
3
287. unicode/utf8 (25) (578) (1) (3) - implements functions and constants to support text encoded in UTF-8.
3
288. unique (1) (552) (7) (4) - The unique package provides facilities for canonicalizing ("interning") comparable values.
3
289. unsafe (81) (271) (1) (3) - contains operations that step around the type safety of Go programs.
3
290. vendor/golang.org/x/crypto/chacha20 (1) (453) (18) (6) - implements the ChaCha20 and XChaCha20 encryption algorithms as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
291. vendor/golang.org/x/crypto/chacha20poly1305 (2) (380) (19) (5) - implements the ChaCha20-Poly1305 AEAD and its extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.
3
292. vendor/golang.org/x/crypto/cryptobyte (3) (1358) (17) (4) - contains types that help with parsing and constructing length-prefixed, binary messages, including ASN.1 DER.
298. vendor/golang.org/x/net/http/httpproxy (1) (373) (19) (4) - provides support for HTTP proxy determination based on environment variables, as provided by net/http's ProxyFromEnvironment function.
3
299. vendor/golang.org/x/net/http2/hpack (2) (1585) (15) (4) - implements HPACK, a compression format for efficiently representing HTTP header fields in the context of HTTP/2.
3
300. vendor/golang.org/x/net/idna (3) (6354) (18) (4) - implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
3
301. vendor/golang.org/x/sys/cpu (1) (759) (14) (6) - implements processor feature detection for various CPU architectures.
303. vendor/golang.org/x/text/transform (2) (709) (10) (6) - provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
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
@@ -2796,28 +2796,28 @@
- indexroutingIndex
- musync.RWMutex
-
+ indexroutingIndex
+ musync.RWMutex
+ // used only when GODEBUG=httpmuxgo121=1
- treeroutingNode
+ treeroutingNode
-
+ Handle registers the handler for the given pattern.
If the given pattern conflicts with one that is already registered
or if the pattern is invalid, Handle panics.
See [ServeMux] for details on valid patterns and conflict rules.
-
+ HandleFunc registers the handler function for the given pattern.
If the given pattern conflicts with one that is already registered
or if the pattern is invalid, HandleFunc panics.
See [ServeMux] for details on valid patterns and conflict rules.
-
+ 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
@@ -2839,18 +2839,18 @@
populate named path wildcards, so r.PathValue will always return
the empty string.
-
+ ServeHTTP dispatches the request to the handler whose
pattern most closely matches the request URL.
-
+ findHandler finds a handler for a request.
If there is a matching handler, it returns it and the pattern that matched.
Otherwise it returns a Redirect or NotFound handler with the path that would match
after the redirect.
-
+ matchOrRedirect looks up a node in the tree that matches the host, method and path.
If the url argument is non-nil, handler also deals with trailing-slash
@@ -2858,11 +2858,11 @@
after appending "/" to the path. If that second match succeeds, the last
return value is the URL to redirect to.
-
+ matchingMethods return a sorted list of all methods that would match with the given host and path.
- (*ServeMux) register(pattern string, handler Handler)
- (*ServeMux) registerErr(patstr string, handler Handler) error
+ (*ServeMux) register(pattern string, handler Handler)
+ (*ServeMux) registerErr(patstr string, handler Handler) error
*ServeMux : Handler
@@ -2872,18 +2872,18 @@
var defaultServeMux
-
+
A Server defines parameters for running an HTTP server.
The zero value for Server is a valid configuration.
-
+ 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.
-
+ 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
@@ -2891,47 +2891,47 @@
If BaseContext is nil, the default is context.Background().
If non-nil, it must return a non-nil context.
-
+ 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.
-
+ ConnState specifies an optional callback function that is
called when a client connection changes state. See the
ConnState type and associated constants for details.
-
+ DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
otherwise responds with 200 OK and Content-Length: 0.
-
+ 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.
-
+ HTTP2 configures HTTP/2 connections.
-
+ // handler to invoke, http.DefaultServeMux if nil
-
+ IdleTimeout is the maximum amount of time to wait for the
next request when keep-alives are enabled. If zero, the value
of ReadTimeout is used. If negative, or if zero and ReadTimeout
is zero or negative, there is no timeout.
-
+ 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.
-
+ Protocols is the set of protocols accepted by the server.
If Protocols includes UnencryptedHTTP2, the server will accept
@@ -2942,7 +2942,7 @@
If TLSNextProto is non-nil and does not contain an "h2" entry,
the default is HTTP/1 only.
-
+ 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
@@ -2950,7 +2950,7 @@
ReadTimeout is used. If negative, or if zero and ReadTimeout
is zero or negative, there is no timeout.
-
+ ReadTimeout is the maximum duration for reading the entire
request, including the body. A zero or negative value means
there will be no timeout.
@@ -2960,7 +2960,7 @@
upload rate, most users will prefer to use
ReadHeaderTimeout. It is valid to use them both.
-
+ 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
@@ -2969,7 +2969,7 @@
SetSessionTicketKeys, use Server.Serve with a TLS Listener
instead.
-
+ 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
@@ -2983,7 +2983,7 @@
Historically, TLSNextProto was used to disable HTTP/2 support.
The Server.Protocols field now provides a simpler way to do this.
-
+ 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
@@ -2991,23 +2991,23 @@
A zero or negative value means there will be no timeout.
- activeConnmap[*conn]struct{}
- disableKeepAlivesatomic.Bool
-
+ activeConnmap[*conn]struct{}
+ disableKeepAlivesatomic.Bool
+ // true when server is in shutdown
- listenerGroupsync.WaitGroup
- listenersmap[*net.Listener]struct{}
- musync.Mutex
-
+ listenerGroupsync.WaitGroup
+ listenersmap[*net.Listener]struct{}
+ musync.Mutex
+ // result of http2.ConfigureServer if used
-
+ // guards setupHTTP2_* init
- onShutdown[]func()
+ onShutdown[]func()
-
+ Close immediately closes all active net.Listeners and any
connections in state [StateNew], [StateActive], or [StateIdle]. For a
graceful shutdown, use [Server.Shutdown].
@@ -3018,7 +3018,7 @@
Close returns any error returned from closing the [Server]'s
underlying Listener(s).
-
+ ListenAndServe listens on the TCP network address s.Addr and then
calls [Serve] to handle requests on incoming connections.
Accepted connections are configured to enable TCP keep-alives.
@@ -3028,7 +3028,7 @@
ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
the returned error is [ErrServerClosed].
-
+ ListenAndServeTLS listens on the TCP network address s.Addr and
then calls [ServeTLS] to handle requests on incoming TLS connections.
Accepted connections are configured to enable TCP keep-alives.
@@ -3045,14 +3045,14 @@
ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
[Server.Close], the returned error is [ErrServerClosed].
-
+ RegisterOnShutdown registers a function to call on [Server.Shutdown].
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.
-
+ Serve accepts incoming connections on the Listener l, creating a
new service goroutine for each. The service goroutines read requests and
then call s.Handler to reply to them.
@@ -3064,7 +3064,7 @@
Serve always returns a non-nil error and closes l.
After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
-
+ 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 s.Handler to reply to them.
@@ -3080,13 +3080,13 @@
ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
returned error is [ErrServerClosed].
-
+ 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.
-
+ 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
@@ -3109,28 +3109,28 @@
future calls to methods such as Serve will return ErrServerClosed.
-
+ closeIdleConns closes all idle connections and reports whether the
server is quiescent.
- (*Server) closeListenersLocked() error
- (*Server) doKeepAlives() bool
- (*Server) idleTimeout() time.Duration
+ (*Server) closeListenersLocked() error
+ (*Server) doKeepAlives() bool
+ (*Server) idleTimeout() time.Duration(*Server) initialReadLimitSize() int64
- (*Server) logf(format string, args ...any)
+ (*Server) logf(format string, args ...any)(*Server) maxHeaderBytes() int Create new connection from rwc.
-
+ onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
configured otherwise. (by setting s.TLSNextProto non-nil)
It must only be called via s.nextProtoOnce (use s.setupHTTP2_*).
- (*Server) onceSetNextProtoDefaults_Serve()
- (*Server) protocols() Protocols
- (*Server) readHeaderTimeout() time.Duration
-
+ (*Server) onceSetNextProtoDefaults_Serve()
+ (*Server) protocols() Protocols
+ (*Server) readHeaderTimeout() time.Duration
+ setupHTTP2_Serve is called from (*Server).Serve and conditionally
configures HTTP/2 on s using a more conservative policy than
setupHTTP2_ServeTLS because Serve is called after tls.Listen,
@@ -3140,16 +3140,16 @@
TestConcurrentServerServe in server_test.go demonstrate some
of the supported use cases and motivations.
-
+ setupHTTP2_ServeTLS conditionally configures HTTP/2 on
s and reports whether there was an error setting it up. If it is
not configured for policy reasons, nil is returned.
-
+ shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
automatic HTTP/2. (which sets up the s.TLSNextProto map)
- (*Server) shuttingDown() bool
+ (*Server) shuttingDown() bool tlsHandshakeTimeout returns the time limit permitted for the TLS
handshake, or zero for unlimited.
@@ -3157,8 +3157,8 @@
It returns the minimum of any positive ReadHeaderTimeout,
ReadTimeout, or WriteTimeout.
- (*Server) trackConn(c *conn, add bool)
-
+ (*Server) trackConn(c *conn, add bool)
+ trackListener adds or removes a net.Listener to the set of tracked
listeners.
@@ -3761,16 +3761,16 @@
*cancelTimerBody : io.ReadCloser
*cancelTimerBody : io.Reader
-
+
checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
It only contains one field (and a pointer field at that), so it
fits in an interface value without an extra allocation.
- c*conn
+ c*conn
- ( checkConnErrorWriter) Write(p []byte) (n int, err error)
+ ( checkConnErrorWriter) Write(p []byte) (n int, err error)
checkConnErrorWriter : internal/bisect.Writer
checkConnErrorWriter : io.Writer
@@ -3955,7 +3955,7 @@
func (*Server).newConn(rwc net.Conn) *conn
- func (*Server).trackConn(c *conn, add bool)
+ func (*Server).trackConn(c *conn, add bool)
globalOptionsHandler responds to "OPTIONS *" requests.
- ( globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)
+ ( globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)
globalOptionsHandler : Handler
@@ -9187,24 +9187,24 @@
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
-
+
initALPNRequest is an HTTP handler that initializes certain
uninitialized fields in its *Request. Such partially-initialized
Requests come from ALPN protocol handlers.
- c*tls.Conn
- ctxcontext.Context
- hserverHandler
+ c*tls.Conn
+ ctxcontext.Context
+ hserverHandler
-
+ BaseContext is an exported but unadvertised [http.Handler] method
recognized by x/net/http2 to pass down a context; the TLSNextProto
API predates context support so we shoehorn through the only
interface we have available.
- ( initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)
+ ( initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)
initALPNRequest : Handler
@@ -9251,19 +9251,19 @@
func Header.sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter)
-
+
loggingConn is used for debugging.
- Connnet.Conn
+ Connnet.Conn
- namestring
+ namestring
- (*loggingConn) Close() (err error)
+ (*loggingConn) Close() (err error) LocalAddr returns the local network address, if known.
- (*loggingConn) Read(p []byte) (n int, err error)
+ (*loggingConn) Read(p []byte) (n int, err error) RemoteAddr returns the remote network address, if known.
@@ -9302,7 +9302,7 @@
some of the data was successfully written.
A zero value for t means Write will not time out.
- (*loggingConn) Write(p []byte) (n int, err error)
+ (*loggingConn) Write(p []byte) (n int, err error)
*loggingConn : net.Conn
*loggingConn : internal/bisect.Writer
@@ -9499,15 +9499,15 @@
nothingWrittenError : error
nothingWrittenError : github.com/go-faster/errors.Wrapper
-
Redirect to a fixed URL
- codeint
- urlstring
+ codeint
+ urlstring
- (*redirectHandler) ServeHTTP(w ResponseWriter, r *Request)
+ (*redirectHandler) ServeHTTP(w ResponseWriter, r *Request)
*redirectHandler : Handler
@@ -10051,12 +10051,12 @@
// a non-1xx header has been (logically) written
- (*response) CloseNotify() <-chan bool
+ (*response) CloseNotify() <-chan bool(*response) EnableFullDuplex() error(*response) Flush()(*response) FlushError() error(*response) Header() Header
-
+ Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter]
and a [Hijacker].
@@ -10110,7 +10110,7 @@
bodyAllowed reports whether a Write is allowed for this response type.
It's illegal to call this before the header has been flushed.
- (*response) closeNotify()
+ (*response) closeNotify()(*response) closedRequestBodyEarly() bool declareTrailer is called for each Trailer header when the
@@ -10130,7 +10130,7 @@
requestTooLarge is called by maxBytesReader when too much input has
been read from the client.
- (*response) sendExpectationFailed()
+ (*response) sendExpectationFailed() shouldReuseConnection reports whether the underlying TCP connection can be reused.
It must only be called after the handler is done executing.
@@ -10279,7 +10279,7 @@
- func (*ServeMux).matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL)
+ func (*ServeMux).matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL)
func exactMatch(n *routingNode, path string) bool
@@ -10374,15 +10374,15 @@
not path -- see comments at ServeMux.
-
+
serverHandler delegates to either the server's Handler or
DefaultServeMux and also handles "OPTIONS *" requests.
- srv*Server
+ srv*Server
-
+ ServeHTTP should be an internal detail,
but widely used packages access it using linkname.
Notable members of the hall of shame include:
@@ -10689,45 +10689,45 @@
*timeoutError : net.timeout
*timeoutError : os.timeout
-
Package-Level Functions (total 300, in which 45 are exported)
-
+
AllowQuerySemicolons returns a handler that serves requests by converting any
unescaped semicolons in the URL query to ampersands, and invoking the handler h.
@@ -11638,7 +11638,7 @@
a valid MIME type: if it cannot determine a more specific one, it
returns "application/octet-stream".
-
+
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.
@@ -11708,11 +11708,11 @@
To make a request with a specified context.Context, use [NewRequestWithContext]
and DefaultClient.Do.
-
+
Handle registers the handler for the given pattern in [DefaultServeMux].
The documentation for [ServeMux] explains how patterns are matched.
-
+
HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
The documentation for [ServeMux] explains how patterns are matched.
@@ -11732,7 +11732,7 @@
To make a request with a specified [context.Context], use [NewRequestWithContext]
and DefaultClient.Do.
-
+
ListenAndServe listens on the TCP network address addr and then calls
[Serve] with handler to handle requests on incoming connections.
Accepted connections are configured to enable TCP keep-alives.
@@ -11741,14 +11741,14 @@
ListenAndServe always returns a non-nil error.
-
+
ListenAndServeTLS acts identically to [ListenAndServe], 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.
-
+
MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
@@ -11844,13 +11844,13 @@
If the ResponseWriter does not support a method, ResponseController returns
an error matching [ErrNotSupported].
-
+
NewServeMux allocates and returns a new [ServeMux].
-
+
NotFound replies to the request with an HTTP 404 not found error.
-
+
NotFoundHandler returns a simple request handler
that replies to each request with a “404 page not found” reply.
@@ -11947,7 +11947,7 @@
After that call, clients can inspect resp.Trailer to find key/value
pairs included in the response trailer.
-
+
Redirect replies to the request with a redirect to url,
which may be a path relative to the request path.
Any non-ASCII characters in url will be percent-encoded,
@@ -11961,7 +11961,7 @@
Setting the Content-Type header to any value, including nil,
disables that behavior.
-
+
RedirectHandler returns a request handler that redirects
each request it receives to the given url using the given
status code.
@@ -11969,7 +11969,7 @@
The provided code should be in the 3xx range and is usually
[StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
-
+
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.
@@ -12060,7 +12060,7 @@
r.URL.Path for selecting the file or directory to serve; only the
file or directory provided in the name argument is used.
-
+
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.
@@ -12083,7 +12083,7 @@
StatusText returns a text for the HTTP status code. It returns the empty
string if the code is unknown.
-
+
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
@@ -12091,7 +12091,7 @@
match exactly: if the prefix in the request contains escaped characters
the reply is also an HTTP 404 not found error.
-
+
TimeoutHandler returns a [Handler] that runs h with the given time limit.
The new Handler calls h.ServeHTTP to handle each request, but if a
@@ -12104,7 +12104,7 @@
TimeoutHandler supports the [Pusher] interface but does not support
the [Hijacker] or [Flusher] interfaces.
-
+
adjustNextProtos adds or removes "http/1.1" and "h2" entries from
a tls.Config.NextProtos list, according to the set of protocols in protos.
@@ -12122,7 +12122,7 @@
Do not remove or change the type signature.
See go.dev/issue/67401.
-
See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
"To receive authorization, the client sends the userid and password,
separated by a single colon (":") character, within a base64
@@ -12143,7 +12143,7 @@
Checks whether chunked is part of the encodings stack.
-
+
cleanPath returns the canonical path for p, eliminating . and .. elements.
@@ -12247,7 +12247,7 @@
etagWeakMatch reports whether a and b match using weak ETag comparison.
Assumes a and b are valid ETags.
-
+
exactMatch reports whether the node's pattern exactly matches the path.
As a special case, if the node is nil, exactMatch return false.
@@ -12318,7 +12318,7 @@
token must be all lowercase.
v may contain mixed cased.
-
http1ServerSupportsRequest reports whether Go's HTTP/1.x server
supports the given request.
@@ -12608,7 +12608,7 @@
localRedirect gives a Moved Permanently response.
It does not convert relative paths to absolute paths like Redirect does.
-
+
logf prints to the ErrorLog of the *Server associated with request r
via ServerContextKey. If there's no associated server, or if ErrorLog
is nil, logging is done via the log package's standard logger.
@@ -12618,7 +12618,7 @@
to a possibly better non-nil error. In particular, it turns OS-specific errors
about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552.
-
parseBasicAuth parses an HTTP Basic Authentication string.
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
@@ -12717,7 +12717,7 @@
an empty string if lastReq scheme is https and newReq scheme is http.
If the referer was explicitly set, then it will continue to be used.
-
relevantCaller searches the call stack for the first function outside of net/http.
The purpose of this function is to provide more helpful error messages.
@@ -12729,7 +12729,7 @@
removeZone removes IPv6 zone identifier from host.
E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"
-
+
requestBodyRemains reports whether future calls to Read
on rc might yield more data.
@@ -12824,7 +12824,7 @@
@@ -12832,7 +12832,7 @@
before ctx's deadline, if any. If ctx does not have a deadline, it
always reports true (the deadline is considered infinite).
-
+
tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
looks like it might've been a misdirected plaintext HTTP request.
@@ -12880,7 +12880,7 @@
DefaultClient is the default [Client] and is used by [Get], [Head], and [Post].
-
+
DefaultServeMux is the default [ServeMux] used by [Serve].
@@ -12913,7 +12913,7 @@
declared size and then attempted to write more bytes than
declared.
-
+
ErrHandlerTimeout is returned on [ResponseWriter] Write calls
in handlers which have timed out.
@@ -12968,7 +12968,7 @@
ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.
-
+
ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
@@ -13018,7 +13018,7 @@
aLongTimeAgo is a non-zero time, far in the past, used for
immediate cancellation of network operations.
-
errCallerOwnsConn is an internal sentinel error used when we hand
off a writable response.Body to the caller. We use this to prevent
closing a net.Conn that is now owned by the caller.
@@ -13083,7 +13083,7 @@
Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running
streaming requests using small frame sizes occupy large buffers initially allocated for prior
requests needing big buffers. The size ranges are as follows:
@@ -13198,7 +13198,7 @@
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
@@ -13352,22 +13352,22 @@
cannot be used to do per-request work; ConnState only notes
the overall state of the connection.
-
+
StateClosed represents a closed connection.
This is a terminal state. Hijacked connections do not
transition to StateClosed.
-
+
StateHijacked represents a hijacked connection.
This is a terminal state. It does not transition to StateClosed.
-
+
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.
-
+
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
@@ -13888,7 +13888,7 @@
TLSNextProto key to use for unencrypted HTTP/2 connections.
Not actually a TLS-negotiated protocol.
-
constoverlapsrelationship = "overlaps" // there is a request that both match, but neither is more specific
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/net/cgo_linux.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/net/cgo_linux.go:1:1// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/src/net/cgo_resnew.go.html b/src/net/cgo_resnew.go.html
index 5816574ac5f..d6023ecd0cd 100644
--- a/src/net/cgo_resnew.go.html
+++ b/src/net/cgo_resnew.go.html
@@ -38,7 +38,7 @@
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/net/cgo_resnew.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/net/cgo_resnew.go:1:1// Copyright 2015 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/src/net/cgo_socknew.go.html b/src/net/cgo_socknew.go.html
index 188fc2195ee..650ed8aacf1 100644
--- a/src/net/cgo_socknew.go.html
+++ b/src/net/cgo_socknew.go.html
@@ -42,7 +42,7 @@
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/net/cgo_socknew.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/net/cgo_socknew.go:1:1// Copyright 2015 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/src/net/cgo_unix_cgo.go.html b/src/net/cgo_unix_cgo.go.html
index 21b8f689a48..fc4b387dd96 100644
--- a/src/net/cgo_unix_cgo.go.html
+++ b/src/net/cgo_unix_cgo.go.html
@@ -92,7 +92,7 @@
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/net/cgo_unix_cgo.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/net/cgo_unix_cgo.go:1:1// Copyright 2022 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/src/net/cgo_unix_cgo_res.go.html b/src/net/cgo_unix_cgo_res.go.html
index 6374e863e2f..db24490abf8 100644
--- a/src/net/cgo_unix_cgo_res.go.html
+++ b/src/net/cgo_unix_cgo_res.go.html
@@ -48,7 +48,7 @@
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/net/cgo_unix_cgo_res.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/net/cgo_unix_cgo_res.go:1:1// Copyright 2022 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/src/net/http/csrf.go.html b/src/net/http/csrf.go.html
index bde1d45b4db..9514ee21028 100644
--- a/src/net/http/csrf.go.html
+++ b/src/net/http/csrf.go.html
@@ -134,7 +134,7 @@
// [Cross-Site Request Forgery (CSRF)]: https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF// [safe methods]: https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTPtypeCrossOriginProtectionstruct {
-bypassatomic.Pointer[ServeMux]
+bypassatomic.Pointer[ServeMux]trustedMusync.RWMutextrustedmap[string]booldenyatomic.Pointer[Handler]
@@ -197,7 +197,7 @@
// AddInsecureBypassPattern can be called concurrently with other methods or// request handling, and applies to future requests.func ( *CrossOriginProtection) ( string) {
-var *ServeMux
+var *ServeMux// Lazily initialize c.bypassfor {
@@ -205,13 +205,13 @@
if != nil {break }
- = NewServeMux()
+ = NewServeMux()if .bypass.CompareAndSwap(nil, ) {break } }
- .Handle(, sentinelHandler)
+ .Handle(, sentinelHandler)}// SetDenyHandler sets a handler to invoke when a request is rejected.
@@ -284,7 +284,7 @@
// be deferred until the last moment.func ( *CrossOriginProtection) ( *Request) bool {if := .bypass.Load(); != nil {
-if , := .Handler(); == sentinelHandler {
+if , := .Handler(); == sentinelHandler {// The request matches a bypass pattern.returntrue }
@@ -304,13 +304,13 @@
// with a 403 Forbidden status or handled with the handler passed// to [CrossOriginProtection.SetDenyHandler].func ( *CrossOriginProtection) ( Handler) Handler {
-returnHandlerFunc(func( ResponseWriter, *Request) {
+returnHandlerFunc(func( ResponseWriter, *Request) {if := .Check(); != nil {if := .deny.Load(); != nil { (*).ServeHTTP(, )return }
-Error(, .Error(), StatusForbidden)
+Error(, .Error(), StatusForbidden)return } .ServeHTTP(, )
diff --git a/src/net/http/fs.go.html b/src/net/http/fs.go.html
index 92304cd944a..eebec91d0a0 100644
--- a/src/net/http/fs.go.html
+++ b/src/net/http/fs.go.html
@@ -819,8 +819,8 @@
}if != nil {
-logf(, "http: error reading directory: %v", )
-Error(, "Error reading directory", StatusInternalServerError)
+logf(, "http: error reading directory: %v", )
+Error(, "Error reading directory", StatusInternalServerError)return }sort.Slice(, func(, int) bool { return .name() < .name() })
@@ -838,7 +838,7 @@
// part of the URL path, and not indicate the start of a query // string or fragment. := url.URL{Path: }
-fmt.Fprintf(, "<a href=\"%s\">%s</a>\n", .String(), htmlReplacer.Replace())
+fmt.Fprintf(, "<a href=\"%s\">%s</a>\n", .String(), htmlReplacer.Replace()) }fmt.Fprintf(, "</pre>\n")}
@@ -874,7 +874,7 @@
httpservecontentkeepheaders.IncNonDefault() }
-Error(, , )
+Error(, , )}// ServeContent replies to the request using the content in the
diff --git a/src/net/http/h2_bundle.go.html b/src/net/http/h2_bundle.go.html
index 4491db5165a..c05dc047487 100644
--- a/src/net/http/h2_bundle.go.html
+++ b/src/net/http/h2_bundle.go.html
@@ -6053,7 +6053,7 @@
// configFromServer merges configuration settings from// net/http.Server.HTTP2Config and http2.Server.
-func ( *Server, *http2Server) http2http2Config {
+func ( *Server, *http2Server) http2http2Config { := http2http2Config{MaxConcurrentStreams: .MaxConcurrentStreams,MaxEncoderHeaderTableSize: .MaxEncoderHeaderTableSize,
@@ -6067,7 +6067,7 @@
PermitProhibitedCipherSuites: .PermitProhibitedCipherSuites,CountError: .CountError, }
-http2fillNetHTTPConfig(&, .HTTP2)
+http2fillNetHTTPConfig(&, .HTTP2)http2setConfigDefaults(&, true)return}
@@ -9214,7 +9214,7 @@
// The configuration conf may be nil.//// ConfigureServer must be called before s begins serving.
-func ( *Server, *http2Server) error {
+func ( *Server, *http2Server) error {if == nil {panic("nil *http.Server") }
@@ -9226,22 +9226,22 @@
errChanPool: sync.Pool{New: func() any { returnmake(chanerror, 1) }}, }if , := , ; .IdleTimeout == 0 {
-if .IdleTimeout != 0 {
- .IdleTimeout = .IdleTimeout
+if .IdleTimeout != 0 {
+ .IdleTimeout = .IdleTimeout } else {
- .IdleTimeout = .ReadTimeout
+ .IdleTimeout = .ReadTimeout } }
- .RegisterOnShutdown(.state.startGracefulShutdown)
+ .RegisterOnShutdown(.state.startGracefulShutdown)
-if .TLSConfig == nil {
- .TLSConfig = new(tls.Config)
- } elseif .TLSConfig.CipherSuites != nil && .TLSConfig.MinVersion < tls.VersionTLS13 {
+if .TLSConfig == nil {
+ .TLSConfig = new(tls.Config)
+ } elseif .TLSConfig.CipherSuites != nil && .TLSConfig.MinVersion < tls.VersionTLS13 {// If they already provided a TLS 1.0–1.2 CipherSuite list, return an // error if it is missing ECDHE_RSA_WITH_AES_128_GCM_SHA256 or // ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. := false
-for , := range .TLSConfig.CipherSuites {
+for , := range .TLSConfig.CipherSuites {switch {casetls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,// Alternative MTI cipher to not discourage ECDSA-only servers.
@@ -9262,19 +9262,19 @@
// during next-proto selection, but using TLS <1.2 with // HTTP/2 is still the client's bug.
- .TLSConfig.PreferServerCipherSuites = true
+ .TLSConfig.PreferServerCipherSuites = true
-if !http2strSliceContains(.TLSConfig.NextProtos, http2NextProtoTLS) {
- .TLSConfig.NextProtos = append(.TLSConfig.NextProtos, http2NextProtoTLS)
+if !http2strSliceContains(.TLSConfig.NextProtos, http2NextProtoTLS) {
+ .TLSConfig.NextProtos = append(.TLSConfig.NextProtos, http2NextProtoTLS) }
-if !http2strSliceContains(.TLSConfig.NextProtos, "http/1.1") {
- .TLSConfig.NextProtos = append(.TLSConfig.NextProtos, "http/1.1")
+if !http2strSliceContains(.TLSConfig.NextProtos, "http/1.1") {
+ .TLSConfig.NextProtos = append(.TLSConfig.NextProtos, "http/1.1") }
-if .TLSNextProto == nil {
- .TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){}
+if .TLSNextProto == nil {
+ .TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){} }
- := func( *Server, net.Conn, Handler, bool) {
+ := func( *Server, net.Conn, Handler, bool) {ifhttp2testHookOnConn != nil {http2testHookOnConn() }
@@ -9297,16 +9297,16 @@
SawClientPreface: , }) }
- .TLSNextProto[http2NextProtoTLS] = func( *Server, *tls.Conn, Handler) {
+ .TLSNextProto[http2NextProtoTLS] = func( *Server, *tls.Conn, Handler) { (, , , false) }// The "unencrypted_http2" TLSNextProto key is used to pass off non-TLS HTTP/2 conns. // // A connection passed in this method has already had the HTTP/2 preface read from it.
- .TLSNextProto[http2nextProtoUnencryptedHTTP2] = func( *Server, *tls.Conn, Handler) {
+ .TLSNextProto[http2nextProtoUnencryptedHTTP2] = func( *Server, *tls.Conn, Handler) { , := http2unencryptedNetConnFromTLSConn()if != nil {
-if := .ErrorLog; != nil {
+if := .ErrorLog; != nil { .Print() } else {log.Print()
@@ -9327,7 +9327,7 @@
// BaseConfig optionally sets the base configuration // for values. If nil, defaults are used.
-BaseConfig *Server
+BaseConfig *Server// Handler specifies which handler to use for processing // requests. If nil, BaseConfig.Handler is used. If BaseConfig
@@ -9356,11 +9356,11 @@
returncontext.Background()}
-func ( *http2ServeConnOpts) () *Server {
+func ( *http2ServeConnOpts) () *Server {if != nil && .BaseConfig != nil {return .BaseConfig }
-returnnew(Server)
+returnnew(Server)}func ( *http2ServeConnOpts) () Handler {
@@ -9368,11 +9368,11 @@
if .Handler != nil {return .Handler }
-if .BaseConfig != nil && .BaseConfig.Handler != nil {
-return .BaseConfig.Handler
+if .BaseConfig != nil && .BaseConfig.Handler != nil {
+return .BaseConfig.Handler } }
-returnDefaultServeMux
+returnDefaultServeMux}// ServeConn serves HTTP/2 requests on the provided connection and
@@ -9440,7 +9440,7 @@
// passes the connection off to us with the deadline already set. // Write deadlines are set per stream in serverConn.newStream. // Disarm the net.Conn write deadline here.
-if .hs.WriteTimeout > 0 {
+if .hs.WriteTimeout > 0 { .conn.SetWriteDeadline(time.Time{}) }
@@ -9557,7 +9557,7 @@
typehttp2serverConnstruct {// Immutable:srv *http2Server
-hs *Server
+hs *Serverconnnet.Connbw *http2bufferedWriter// writing to connhandlerHandler
@@ -9623,7 +9623,7 @@
}func ( *http2serverConn) () uint32 {
- := .hs.MaxHeaderBytes
+ := .hs.MaxHeaderBytesif <= 0 { = DefaultMaxHeaderBytes }
@@ -9705,9 +9705,9 @@
// setConnState calls the net/http ConnState hook for this connection, if configured.// Note that the net/http package does StateNew and StateClosed for us.// There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
-func ( *http2serverConn) ( ConnState) {
-if .hs.ConnState != nil {
- .hs.ConnState(.conn, )
+func ( *http2serverConn) ( ConnState) {
+if .hs.ConnState != nil {
+ .hs.ConnState(.conn, ) }}
@@ -9718,7 +9718,7 @@
}func ( *http2serverConn) ( string, ...interface{}) {
-if := .hs.ErrorLog; != nil {
+if := .hs.ErrorLog; != nil { .Printf(, ...) } else {log.Printf(, ...)
@@ -9932,8 +9932,8 @@
// "StateNew" state. We can't go directly to idle, though. // Active means we read some data and anticipate a request. We'll // do another Active when we get a HEADERS frame.
- .setConnState(StateActive)
- .setConnState(StateIdle)
+ .setConnState(StateActive)
+ .setConnState(StateIdle)if .srv.IdleTimeout > 0 { .idleTimer = time.AfterFunc(.srv.IdleTimeout, .onIdleTimer)
@@ -10701,7 +10701,7 @@
}delete(.streams, .id)iflen(.streams) == 0 {
- .setConnState(StateIdle)
+ .setConnState(StateIdle)if .srv.IdleTimeout > 0 && .idleTimer != nil { .idleTimer.Reset(.srv.IdleTimeout) }
@@ -11086,9 +11086,9 @@
// similar to how the http1 server works. Here it's // technically more like the http1 Server's ReadHeaderTimeout // (in Go 1.8), though. That's a more sane option anyway.
-if .hs.ReadTimeout > 0 {
+if .hs.ReadTimeout > 0 { .conn.SetReadDeadline(time.Time{})
- .readDeadline = time.AfterFunc(.hs.ReadTimeout, .onReadTimeout)
+ .readDeadline = time.AfterFunc(.hs.ReadTimeout, .onReadTimeout) }return .scheduleHandler(, , , )
@@ -11107,7 +11107,7 @@
// Disable any read deadline set by the net/http package // prior to the upgrade.
-if .hs.ReadTimeout > 0 {
+if .hs.ReadTimeout > 0 { .conn.SetReadDeadline(time.Time{}) }
@@ -11185,8 +11185,8 @@
.flow.conn = &.flow// link to conn-level counter .flow.add(.initialStreamSendWindowSize) .inflow.init(.initialStreamRecvWindowSize)
-if .hs.WriteTimeout > 0 {
- .writeDeadline = time.AfterFunc(.hs.WriteTimeout, .onWriteTimeout)
+if .hs.WriteTimeout > 0 {
+ .writeDeadline = time.AfterFunc(.hs.WriteTimeout, .onWriteTimeout) } .streams[] =
@@ -11197,7 +11197,7 @@
.curClientStreams++ }if .curOpenStreams() == 1 {
- .setConnState(StateActive)
+ .setConnState(StateActive) }return
@@ -12270,16 +12270,16 @@
returnnil}
-func ( error) HandlerFunc {
+func ( error) HandlerFunc {returnfunc( ResponseWriter, *Request) {
-Error(, .Error(), StatusBadRequest)
+Error(, .Error(), StatusBadRequest) }}// h1ServerKeepAlivesDisabled reports whether hs has its keep-alives// disabled. See comments on h1ServerShutdownChan above for why// the code is written this way.
-func ( *Server) bool {
+func ( *Server) bool {varinterface{} = typeinterface { () bool
diff --git a/src/net/http/pattern.go.html b/src/net/http/pattern.go.html
index 83869dc6995..f41ecb5e7b9 100644
--- a/src/net/http/pattern.go.html
+++ b/src/net/http/pattern.go.html
@@ -325,7 +325,7 @@
// An unclean path with a method that is not CONNECT can never match, // because paths are cleaned before matching.
-if != "" && != "CONNECT" && != cleanPath() {
+if != "" && != "CONNECT" && != cleanPath() {returnnil, errors.New("non-CONNECT pattern with unclean path can never match") }
diff --git a/src/net/http/servemux121.go.html b/src/net/http/servemux121.go.html
index fced0efddb7..e52d5590eb3 100644
--- a/src/net/http/servemux121.go.html
+++ b/src/net/http/servemux121.go.html
@@ -259,7 +259,7 @@
if == nil {panic("http: nil handler") }
- .handle(, HandlerFunc())
+ .handle(, HandlerFunc())}// Formerly ServeMux.Handler.
@@ -271,7 +271,7 @@
// the /tree -> /tree/ redirect applies to CONNECT requests // but the path canonicalization does not.if , := .redirectToPathSlash(.URL.Host, .URL.Path, .URL); {
-returnRedirectHandler(.String(), StatusMovedPermanently), .Path
+returnRedirectHandler(.String(), StatusMovedPermanently), .Path }return .handler(.Host, .URL.Path)
@@ -279,19 +279,19 @@
// All other requests have any port stripped and path cleaned // before passing to mux.handler.
- := stripHostPort(.Host)
- := cleanPath(.URL.Path)
+ := stripHostPort(.Host)
+ := cleanPath(.URL.Path)// If the given path is /tree and its handler is not registered, // redirect for /tree/.if , := .redirectToPathSlash(, , .URL); {
-returnRedirectHandler(.String(), StatusMovedPermanently), .Path
+returnRedirectHandler(.String(), StatusMovedPermanently), .Path }if != .URL.Path { _, = .handler(, ) := &url.URL{Path: , RawQuery: .URL.RawQuery}
-returnRedirectHandler(.String(), StatusMovedPermanently),
+returnRedirectHandler(.String(), StatusMovedPermanently), }return .handler(, .URL.Path)
@@ -311,7 +311,7 @@
, = .match() }if == nil {
- , = NotFoundHandler(), ""
+ , = NotFoundHandler(), "" }return}
diff --git a/src/net/http/server.go.html b/src/net/http/server.go.html
index cef5601c148..20084f28c1c 100644
--- a/src/net/http/server.go.html
+++ b/src/net/http/server.go.html
@@ -1842,7 +1842,7 @@
typeconnstruct {// server is the server on which the connection arrived. // Immutable; never nil.
-server *Server
+server *Server// cancelCtx cancels the connection-level context.cancelCtxcontext.CancelFunc
@@ -1920,7 +1920,7 @@
.bufw.Reset() = bufio.NewReadWriter(.bufr, .bufw)
- .setState(, StateHijacked, runHooks)
+ .setState(, StateHijacked, runHooks)return}
@@ -2219,13 +2219,13 @@
constdebugServerConnections = false// Create new connection from rwc.
-func ( *Server) ( net.Conn) *conn {
+func ( *Server) ( net.Conn) *conn { := &conn{server: ,rwc: , }ifdebugServerConnections {
- .rwc = newLoggingConn("server", .rwc)
+ .rwc = newLoggingConn("server", .rwc) }return}
@@ -2360,7 +2360,7 @@
} .conn.cancelCtx()if := .conn.curReq.Load(); != nil {
- .closeNotify()
+ .closeNotify() }}
@@ -2482,14 +2482,14 @@
// This can be overridden by setting [Server.MaxHeaderBytes].constDefaultMaxHeaderBytes = 1 << 20// 1 MB
-func ( *Server) () int {
-if .MaxHeaderBytes > 0 {
-return .MaxHeaderBytes
+func ( *Server) () int {
+if .MaxHeaderBytes > 0 {
+return .MaxHeaderBytes }returnDefaultMaxHeaderBytes}
-func ( *Server) () int64 {
+func ( *Server) () int64 {returnint64(.maxHeaderBytes()) + 4096// bufio slop}
@@ -2498,12 +2498,12 @@
//// It returns the minimum of any positive ReadHeaderTimeout,// ReadTimeout, or WriteTimeout.
-func ( *Server) () time.Duration {
+func ( *Server) () time.Duration {vartime.Durationfor , := range [...]time.Duration{
- .ReadHeaderTimeout,
- .ReadTimeout,
- .WriteTimeout,
+ .ReadHeaderTimeout,
+ .ReadTimeout,
+ .WriteTimeout, } {if <= 0 {continue
@@ -2568,10 +2568,10 @@
:= time.Now()vartime.Time// or zero if none
-if := .server.ReadTimeout; > 0 {
+if := .server.ReadTimeout; > 0 { = .Add() }
-if := .server.WriteTimeout; > 0 {
+if := .server.WriteTimeout; > 0 {deferfunc() { .rwc.SetWriteDeadline(time.Now().Add()) }()
@@ -2581,7 +2581,7 @@
if .lastMethod == "POST" {// RFC 7230 section 3 tolerance for old buggy clients. , := .bufr.Peek(4) // ReadRequest will get err below
- .bufr.Discard(numLeadingCRorLF())
+ .bufr.Discard(numLeadingCRorLF()) } , := readRequest(.bufr)if != nil {
@@ -2727,12 +2727,12 @@
func ( *response) ( int) {if .conn.hijacked() { := relevantCaller()
- .conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", .Function, path.Base(.File), .Line)
+ .conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", .Function, path.Base(.File), .Line)return }if .wroteHeader { := relevantCaller()
- .conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", .Function, path.Base(.File), .Line)
+ .conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", .Function, path.Base(.File), .Line)return }checkWriteHeaderCode()
@@ -2770,7 +2770,7 @@
if == nil && >= 0 { .contentLength = } else {
- .conn.server.logf("http: invalid Content-Length of %q", )
+ .conn.server.logf("http: invalid Content-Length of %q", ) .handlerHeader.Del("Content-Length") } }
@@ -2840,7 +2840,7 @@
.wroteHeader = true := .res
- := .conn.server.doKeepAlives()
+ := .conn.server.doKeepAlives() := .req.Method == "HEAD"// header is written out to w.conn.buf below. Depending on the
@@ -3046,7 +3046,7 @@
if && && != "identity" {// TODO: return an error if WriteHeader gets a return parameter // For now just ignore the Content-Length.
- .conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
+ .conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d", , .contentLength) ("Content-Length") = false
@@ -3208,7 +3208,7 @@
if .conn.hijacked() {if > 0 { := relevantCaller()
- .conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", .Function, path.Base(.File), .Line)
+ .conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", .Function, path.Base(.File), .Line) }return0, ErrHijacked }
@@ -3404,13 +3404,13 @@
skipHooks = false)
-func ( *conn) ( net.Conn, ConnState, bool) {
+func ( *conn) ( net.Conn, ConnState, bool) { := .serverswitch {
-caseStateNew:
- .trackConn(, true)
-caseStateHijacked, StateClosed:
- .trackConn(, false)
+caseStateNew:
+ .trackConn(, true)
+caseStateHijacked, StateClosed:
+ .trackConn(, false) }if > 0xff || < 0 {panic("internal error")
@@ -3420,14 +3420,14 @@
if ! {return }
-if := .ConnState; != nil {
+if := .ConnState; != nil { (, ) }}
-func ( *conn) () ( ConnState, int64) {
+func ( *conn) () ( ConnState, int64) { := .curState.Load()
-returnConnState( & 0xff), int64( >> 8)
+returnConnState( & 0xff), int64( >> 8)}// badRequestError is a literal string (used by in the server in HTML,
@@ -3483,7 +3483,7 @@
const = 64 << 10 := make([]byte, ) = [:runtime.Stack(, false)]
- .server.logf("http: panic serving %v: %v\n%s", .remoteAddr, , )
+ .server.logf("http: panic serving %v: %v\n%s", .remoteAddr, , ) }if != nil { .cancelCtx()
@@ -3495,7 +3495,7 @@
.reqBody.Close() } .close()
- .setState(.rwc, StateClosed, runHooks)
+ .setState(.rwc, StateClosed, runHooks) } }()
@@ -3511,14 +3511,14 @@
// TLS, assume they're speaking plaintext HTTP and write a // 400 response on the TLS conn's underlying net.Conn.varstring
-if , := .(tls.RecordHeaderError); && .Conn != nil && tlsRecordHeaderLooksLikeHTTP(.RecordHeader) {
+if , := .(tls.RecordHeaderError); && .Conn != nil && tlsRecordHeaderLooksLikeHTTP(.RecordHeader) {io.WriteString(.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n") .Conn.Close() = "client sent an HTTP request to an HTTPS server" } else { = .Error() }
- .server.logf("http: TLS handshake error from %s: %v", .rwc.RemoteAddr(), )
+ .server.logf("http: TLS handshake error from %s: %v", .rwc.RemoteAddr(), )return }// Restore Conn-level deadlines.
@@ -3529,12 +3529,12 @@
.tlsState = new(tls.ConnectionState) *.tlsState = .ConnectionState()if := .tlsState.NegotiatedProtocol; validNextProto() {
-if := .server.TLSNextProto[]; != nil {
- := initALPNRequest{, , serverHandler{.server}}
+if := .server.TLSNextProto[]; != nil {
+ := initALPNRequest{, , serverHandler{.server}}// Mark freshly created HTTP/2 as active and prevent any server state hooks // from being run on these connections. This prevents closeIdleConns from // closing such connections. See issue https://golang.org/issue/39776.
- .setState(.rwc, StateActive, skipHooks)
+ .setState(.rwc, StateActive, skipHooks) (.server, , ) }return
@@ -3557,13 +3557,13 @@
.r = &connReader{conn: , rwc: .rwc} .bufr = newBufioReader(.r)
- .bufw = newBufioWriterSize(checkConnErrorWriter{}, 4<<10)
+ .bufw = newBufioWriterSize(checkConnErrorWriter{}, 4<<10)
-if := .server.readHeaderTimeout(); > 0 {
+if := .server.readHeaderTimeout(); > 0 { .rwc.SetReadDeadline(time.Now().Add()) }
- := .server.protocols()
+ := .server.protocols()if .tlsState == nil && .UnencryptedHTTP2() {if .maybeServeUnencryptedHTTP2() {return
@@ -3577,9 +3577,9 @@
, := .readRequest()if .r.remain != .server.initialReadLimitSize() {// If we read any bytes off the wire, we're active.
- .setState(.rwc, StateActive, runHooks)
+ .setState(.rwc, StateActive, runHooks) }
-if .server.shuttingDown() {
+if .server.shuttingDown() {return }if != nil {
@@ -3632,14 +3632,14 @@
.canWriteContinue.Store(true) } } elseif .Header.get("Expect") != "" {
- .sendExpectationFailed()
+ .sendExpectationFailed()return } .curReq.Store()
-ifrequestBodyRemains(.Body) {
-registerOnHitEOF(.Body, .conn.r.startBackgroundRead)
+ifrequestBodyRemains(.Body) {
+registerOnHitEOF(.Body, .conn.r.startBackgroundRead) } else { .conn.r.startBackgroundRead() }
@@ -3652,7 +3652,7 @@
// But we're not going to implement HTTP pipelining because it // was never deployed in the wild and the answer is HTTP/2. =
-serverHandler{.server}.ServeHTTP(, .req)
+serverHandler{.server}.ServeHTTP(, .req) = nil .cancelCtx()if .hijacked() {
@@ -3667,10 +3667,10 @@
}return }
- .setState(.rwc, StateIdle, runHooks)
+ .setState(.rwc, StateIdle, runHooks) .curReq.Store(nil)
-if !.conn.server.doKeepAlives() {
+if !.conn.server.doKeepAlives() {// We're in shutdown mode. We might've replied // to the user without "Connection: close" and // they might think they can send another
@@ -3678,7 +3678,7 @@
return }
-if := .server.idleTimeout(); > 0 {
+if := .server.idleTimeout(); > 0 { .rwc.SetReadDeadline(time.Now().Add()) } else { .rwc.SetReadDeadline(time.Time{})
@@ -3692,7 +3692,7 @@
return }
-if := .server.readHeaderTimeout(); > 0 {
+if := .server.readHeaderTimeout(); > 0 { .rwc.SetReadDeadline(time.Now().Add()) } else { .rwc.SetReadDeadline(time.Time{})
@@ -3707,7 +3707,7 @@
typeunencryptedHTTP2Requeststruct {ctxcontext.Contextcnet.Conn
-hserverHandler
+hserverHandler}func ( unencryptedHTTP2Request) () context.Context { return .ctx }
@@ -3719,7 +3719,7 @@
if .RemoteAddr == "" { .RemoteAddr = .c.RemoteAddr().String() }
- .h.ServeHTTP(, )
+ .h.ServeHTTP(, )}// unencryptedNetConnInTLSConn is used to pass an unencrypted net.Conn to
@@ -3742,7 +3742,7 @@
constnextProtoUnencryptedHTTP2 = "unencrypted_http2"func ( *conn) ( context.Context) bool {
- , := .server.TLSNextProto[nextProtoUnencryptedHTTP2]
+ , := .server.TLSNextProto[nextProtoUnencryptedHTTP2]if ! {returnfalse }
@@ -3758,1905 +3758,1907 @@
if !(, []byte("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")) {returnfalse }
- .setState(.rwc, StateActive, skipHooks)
- := unencryptedHTTP2Request{, .rwc, serverHandler{.server}}
- (.server, unencryptedTLSConn(.rwc), )
-returntrue
-}
-
-func ( *response) () {
-// TODO(bradfitz): let ServeHTTP handlers handle
- // requests with non-standard expectation[s]? Seems
- // theoretical at best, and doesn't fit into the
- // current ServeHTTP model anyway. We'd need to
- // make the ResponseWriter an optional
- // "ExpectReplier" interface or something.
- //
- // For now we'll just obey RFC 7231 5.1.1 which says
- // "A server that receives an Expect field-value other
- // than 100-continue MAY respond with a 417 (Expectation
- // Failed) status code to indicate that the unexpected
- // expectation cannot be met."
- .Header().Set("Connection", "close")
- .WriteHeader(StatusExpectationFailed)
- .finishRequest()
-}
-
-// Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter]
-// and a [Hijacker].
-func ( *response) () ( net.Conn, *bufio.ReadWriter, error) {
-if .handlerDone.Load() {
-panic("net/http: Hijack called after ServeHTTP finished")
- }
- .disableWriteContinue()
-if .wroteHeader {
- .cw.flush()
- }
-
- := .conn
- .mu.Lock()
-defer .mu.Unlock()
-
-// Release the bufioWriter that writes to the chunk writer, it is not
- // used after a connection has been hijacked.
- , , = .hijackLocked()
-if == nil {
-putBufioWriter(.w)
- .w = nil
- }
-return , ,
-}
-
-func ( *response) () <-chanbool {
- .lazyCloseNotifyMu.Lock()
-defer .lazyCloseNotifyMu.Unlock()
-if .handlerDone.Load() {
-panic("net/http: CloseNotify called after ServeHTTP finished")
- }
-if .closeNotifyCh == nil {
- .closeNotifyCh = make(chanbool, 1)
-if .closeNotifyTriggered {
- .closeNotifyCh <- true// action prior closeNotify call
- }
- }
-return .closeNotifyCh
-}
-
-func ( *response) () {
- .lazyCloseNotifyMu.Lock()
-defer .lazyCloseNotifyMu.Unlock()
-if .closeNotifyTriggered {
-return// already triggered
- }
- .closeNotifyTriggered = true
-if .closeNotifyCh != nil {
- .closeNotifyCh <- true
- }
-}
-
-func ( io.ReadCloser, func()) {
-switch v := .(type) {
-case *expectContinueReader:
- (.readCloser, )
-case *body:
- .registerOnHitEOF()
-default:
-panic("unexpected type " + fmt.Sprintf("%T", ))
- }
-}
-
-// requestBodyRemains reports whether future calls to Read
-// on rc might yield more data.
-func ( io.ReadCloser) bool {
-if == NoBody {
-returnfalse
- }
-switch v := .(type) {
-case *expectContinueReader:
-return (.readCloser)
-case *body:
-return .bodyRemains()
-default:
-panic("unexpected type " + fmt.Sprintf("%T", ))
- }
-}
-
-// 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
-// [Handler] that calls f.
-typeHandlerFuncfunc(ResponseWriter, *Request)
-
-// ServeHTTP calls f(w, r).
-func ( HandlerFunc) ( ResponseWriter, *Request) {
- (, )
-}
-
-// Helper handlers
+ .setState(.rwc, StateActive, skipHooks)
+ .rwc.SetReadDeadline(time.Time{})
+ .rwc.SetWriteDeadline(time.Time{})
+ := unencryptedHTTP2Request{, .rwc, serverHandler{.server}}
+ (.server, unencryptedTLSConn(.rwc), )
+returntrue
+}
+
+func ( *response) () {
+// TODO(bradfitz): let ServeHTTP handlers handle
+ // requests with non-standard expectation[s]? Seems
+ // theoretical at best, and doesn't fit into the
+ // current ServeHTTP model anyway. We'd need to
+ // make the ResponseWriter an optional
+ // "ExpectReplier" interface or something.
+ //
+ // For now we'll just obey RFC 7231 5.1.1 which says
+ // "A server that receives an Expect field-value other
+ // than 100-continue MAY respond with a 417 (Expectation
+ // Failed) status code to indicate that the unexpected
+ // expectation cannot be met."
+ .Header().Set("Connection", "close")
+ .WriteHeader(StatusExpectationFailed)
+ .finishRequest()
+}
+
+// Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter]
+// and a [Hijacker].
+func ( *response) () ( net.Conn, *bufio.ReadWriter, error) {
+if .handlerDone.Load() {
+panic("net/http: Hijack called after ServeHTTP finished")
+ }
+ .disableWriteContinue()
+if .wroteHeader {
+ .cw.flush()
+ }
+
+ := .conn
+ .mu.Lock()
+defer .mu.Unlock()
+
+// Release the bufioWriter that writes to the chunk writer, it is not
+ // used after a connection has been hijacked.
+ , , = .hijackLocked()
+if == nil {
+putBufioWriter(.w)
+ .w = nil
+ }
+return , ,
+}
+
+func ( *response) () <-chanbool {
+ .lazyCloseNotifyMu.Lock()
+defer .lazyCloseNotifyMu.Unlock()
+if .handlerDone.Load() {
+panic("net/http: CloseNotify called after ServeHTTP finished")
+ }
+if .closeNotifyCh == nil {
+ .closeNotifyCh = make(chanbool, 1)
+if .closeNotifyTriggered {
+ .closeNotifyCh <- true// action prior closeNotify call
+ }
+ }
+return .closeNotifyCh
+}
+
+func ( *response) () {
+ .lazyCloseNotifyMu.Lock()
+defer .lazyCloseNotifyMu.Unlock()
+if .closeNotifyTriggered {
+return// already triggered
+ }
+ .closeNotifyTriggered = true
+if .closeNotifyCh != nil {
+ .closeNotifyCh <- true
+ }
+}
+
+func ( io.ReadCloser, func()) {
+switch v := .(type) {
+case *expectContinueReader:
+ (.readCloser, )
+case *body:
+ .registerOnHitEOF()
+default:
+panic("unexpected type " + fmt.Sprintf("%T", ))
+ }
+}
+
+// requestBodyRemains reports whether future calls to Read
+// on rc might yield more data.
+func ( io.ReadCloser) bool {
+if == NoBody {
+returnfalse
+ }
+switch v := .(type) {
+case *expectContinueReader:
+return (.readCloser)
+case *body:
+return .bodyRemains()
+default:
+panic("unexpected type " + fmt.Sprintf("%T", ))
+ }
+}
+
+// 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
+// [Handler] that calls f.
+typeHandlerFuncfunc(ResponseWriter, *Request)
+
+// ServeHTTP calls f(w, r).
+func ( HandlerFunc) ( ResponseWriter, *Request) {
+ (, )
+}
-// 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.
-//
-// Error deletes the Content-Length header,
-// sets Content-Type to “text/plain; charset=utf-8”,
-// and sets X-Content-Type-Options to “nosniff”.
-// This configures the header properly for the error message,
-// in case the caller had set it up expecting a successful output.
-func ( ResponseWriter, string, int) {
- := .Header()
-
-// Delete the Content-Length header, which might be for some other content.
- // Assuming the error string fits in the writer's buffer, we'll figure
- // out the correct Content-Length for it later.
- //
- // We don't delete Content-Encoding, because some middleware sets
- // Content-Encoding: gzip and wraps the ResponseWriter to compress on-the-fly.
- // See https://go.dev/issue/66343.
- .Del("Content-Length")
-
-// There might be content type already set, but we reset it to
- // text/plain for the error message.
- .Set("Content-Type", "text/plain; charset=utf-8")
- .Set("X-Content-Type-Options", "nosniff")
- .WriteHeader()
-fmt.Fprintln(, )
-}
-
-// NotFound replies to the request with an HTTP 404 not found error.
-func ( ResponseWriter, *Request) { Error(, "404 page not found", StatusNotFound) }
-
-// NotFoundHandler returns a simple request handler
-// that replies to each request with a “404 page not found” reply.
-func () Handler { returnHandlerFunc(NotFound) }
-
-// 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.
-func ( string, Handler) Handler {
-if == "" {
-return
- }
-returnHandlerFunc(func( ResponseWriter, *Request) {
- := strings.TrimPrefix(.URL.Path, )
- := strings.TrimPrefix(.URL.RawPath, )
-iflen() < len(.URL.Path) && (.URL.RawPath == "" || len() < len(.URL.RawPath)) {
- := new(Request)
- * = *
- .URL = new(url.URL)
- *.URL = *.URL
- .URL.Path =
- .URL.RawPath =
- .ServeHTTP(, )
- } else {
-NotFound(, )
- }
- })
-}
-
-// Redirect replies to the request with a redirect to url,
-// which may be a path relative to the request path.
-// Any non-ASCII characters in url will be percent-encoded,
-// but existing percent encodings will not be changed.
-//
-// The provided code should be in the 3xx range and is usually
-// [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
-//
-// If the Content-Type header has not been set, [Redirect] 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.
-func ( ResponseWriter, *Request, string, int) {
-if , := urlpkg.Parse(); == nil {
-// If url was relative, make its path absolute by
- // combining with request path.
- // The client would probably do this for us,
- // but doing it ourselves is more reliable.
- // See RFC 7231, section 7.1.2
-if .Scheme == "" && .Host == "" {
- := .URL.EscapedPath()
-if == "" { // should not happen, but avoid a crash if it does
- = "/"
- }
-
-// no leading http://server
-if == "" || [0] != '/' {
-// make relative path absolute
- , := path.Split()
- = +
- }
-
-varstring
-if := strings.Index(, "?"); != -1 {
- , = [:], [:]
- }
-
-// clean up but preserve trailing slash
- := strings.HasSuffix(, "/")
- = path.Clean()
-if && !strings.HasSuffix(, "/") {
- += "/"
- }
- +=
- }
- }
-
- := .Header()
+// Helper handlers
+
+// 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.
+//
+// Error deletes the Content-Length header,
+// sets Content-Type to “text/plain; charset=utf-8”,
+// and sets X-Content-Type-Options to “nosniff”.
+// This configures the header properly for the error message,
+// in case the caller had set it up expecting a successful output.
+func ( ResponseWriter, string, int) {
+ := .Header()
+
+// Delete the Content-Length header, which might be for some other content.
+ // Assuming the error string fits in the writer's buffer, we'll figure
+ // out the correct Content-Length for it later.
+ //
+ // We don't delete Content-Encoding, because some middleware sets
+ // Content-Encoding: gzip and wraps the ResponseWriter to compress on-the-fly.
+ // See https://go.dev/issue/66343.
+ .Del("Content-Length")
+
+// There might be content type already set, but we reset it to
+ // text/plain for the error message.
+ .Set("Content-Type", "text/plain; charset=utf-8")
+ .Set("X-Content-Type-Options", "nosniff")
+ .WriteHeader()
+fmt.Fprintln(, )
+}
+
+// NotFound replies to the request with an HTTP 404 not found error.
+func ( ResponseWriter, *Request) { Error(, "404 page not found", StatusNotFound) }
+
+// NotFoundHandler returns a simple request handler
+// that replies to each request with a “404 page not found” reply.
+func () Handler { returnHandlerFunc(NotFound) }
+
+// 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.
+func ( string, Handler) Handler {
+if == "" {
+return
+ }
+returnHandlerFunc(func( ResponseWriter, *Request) {
+ := strings.TrimPrefix(.URL.Path, )
+ := strings.TrimPrefix(.URL.RawPath, )
+iflen() < len(.URL.Path) && (.URL.RawPath == "" || len() < len(.URL.RawPath)) {
+ := new(Request)
+ * = *
+ .URL = new(url.URL)
+ *.URL = *.URL
+ .URL.Path =
+ .URL.RawPath =
+ .ServeHTTP(, )
+ } else {
+NotFound(, )
+ }
+ })
+}
+
+// Redirect replies to the request with a redirect to url,
+// which may be a path relative to the request path.
+// Any non-ASCII characters in url will be percent-encoded,
+// but existing percent encodings will not be changed.
+//
+// The provided code should be in the 3xx range and is usually
+// [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
+//
+// If the Content-Type header has not been set, [Redirect] 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.
+func ( ResponseWriter, *Request, string, int) {
+if , := urlpkg.Parse(); == nil {
+// If url was relative, make its path absolute by
+ // combining with request path.
+ // The client would probably do this for us,
+ // but doing it ourselves is more reliable.
+ // See RFC 7231, section 7.1.2
+if .Scheme == "" && .Host == "" {
+ := .URL.EscapedPath()
+if == "" { // should not happen, but avoid a crash if it does
+ = "/"
+ }
+
+// no leading http://server
+if == "" || [0] != '/' {
+// make relative path absolute
+ , := path.Split()
+ = +
+ }
+
+varstring
+if := strings.Index(, "?"); != -1 {
+ , = [:], [:]
+ }
+
+// clean up but preserve trailing slash
+ := strings.HasSuffix(, "/")
+ = path.Clean()
+if && !strings.HasSuffix(, "/") {
+ += "/"
+ }
+ +=
+ }
+ }
-// RFC 7231 notes that a short HTML body is usually included in
- // the response because older user agents may not understand 301/307.
- // Do it only if the request didn't already have a Content-Type header.
- , := ["Content-Type"]
-
- .Set("Location", hexEscapeNonASCII())
-if ! && (.Method == "GET" || .Method == "HEAD") {
- .Set("Content-Type", "text/html; charset=utf-8")
- }
- .WriteHeader()
-
-// Shouldn't send the body for POST or HEAD; that leaves GET.
-if ! && .Method == "GET" {
- := "<a href=\"" + htmlEscape() + "\">" + StatusText() + "</a>.\n"
-fmt.Fprintln(, )
- }
-}
-
-varhtmlReplacer = strings.NewReplacer(
-"&", "&",
-"<", "<",
-">", ">",
-// """ is shorter than """.
-`"`, """,
-// "'" is shorter than "'" and apos was not in HTML until HTML5.
-"'", "'",
-)
-
-func ( string) string {
-returnhtmlReplacer.Replace()
-}
-
-// Redirect to a fixed URL
-typeredirectHandlerstruct {
-urlstring
-codeint
-}
-
-func ( *redirectHandler) ( ResponseWriter, *Request) {
-Redirect(, , .url, .code)
-}
-
-// RedirectHandler returns a request handler that redirects
-// each request it receives to the given url using the given
-// status code.
-//
-// The provided code should be in the 3xx range and is usually
-// [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
-func ( string, int) Handler {
-return &redirectHandler{, }
-}
-
-// 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.
-//
-// # Patterns
+ := .Header()
+
+// RFC 7231 notes that a short HTML body is usually included in
+ // the response because older user agents may not understand 301/307.
+ // Do it only if the request didn't already have a Content-Type header.
+ , := ["Content-Type"]
+
+ .Set("Location", hexEscapeNonASCII())
+if ! && (.Method == "GET" || .Method == "HEAD") {
+ .Set("Content-Type", "text/html; charset=utf-8")
+ }
+ .WriteHeader()
+
+// Shouldn't send the body for POST or HEAD; that leaves GET.
+if ! && .Method == "GET" {
+ := "<a href=\"" + htmlEscape() + "\">" + StatusText() + "</a>.\n"
+fmt.Fprintln(, )
+ }
+}
+
+varhtmlReplacer = strings.NewReplacer(
+"&", "&",
+"<", "<",
+">", ">",
+// """ is shorter than """.
+`"`, """,
+// "'" is shorter than "'" and apos was not in HTML until HTML5.
+"'", "'",
+)
+
+func ( string) string {
+returnhtmlReplacer.Replace()
+}
+
+// Redirect to a fixed URL
+typeredirectHandlerstruct {
+urlstring
+codeint
+}
+
+func ( *redirectHandler) ( ResponseWriter, *Request) {
+Redirect(, , .url, .code)
+}
+
+// RedirectHandler returns a request handler that redirects
+// each request it receives to the given url using the given
+// status code.
+//
+// The provided code should be in the 3xx range and is usually
+// [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
+func ( string, int) Handler {
+return &redirectHandler{, }
+}
+
+// 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.//
-// Patterns can match the method, host and path of a request.
-// Some examples:
-//
-// - "/index.html" matches the path "/index.html" for any host and method.
-// - "GET /static/" matches a GET request whose path begins with "/static/".
-// - "example.com/" matches any request to the host "example.com".
-// - "example.com/{$}" matches requests with host "example.com" and path "/".
-// - "/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.
-//
-// In general, a pattern looks like
+// # Patterns
+//
+// Patterns can match the method, host and path of a request.
+// Some examples:
+//
+// - "/index.html" matches the path "/index.html" for any host and method.
+// - "GET /static/" matches a GET request whose path begins with "/static/".
+// - "example.com/" matches any request to the host "example.com".
+// - "example.com/{$}" matches requests with host "example.com" and path "/".
+// - "/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.//
-// [METHOD ][HOST]/[PATH]
+// In general, a pattern looks like//
-// All three parts are optional; "/" is a valid pattern.
-// If METHOD is present, it must be followed by at least one space or tab.
-//
-// Literal (that is, non-wildcard) parts of a pattern match
-// the corresponding parts of a request case-sensitively.
-//
-// 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.
-//
-// A pattern with no host matches every host.
-// A pattern with a host matches URLs on that host only.
-//
-// 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.
-//
-// 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 [Request.PathValue] with the wildcard's name.
-// A trailing slash in a path acts as an anonymous "..." wildcard.
-//
-// The special wildcard {$} matches only the end of the URL.
-// For example, the pattern "/{$}" matches only the path "/",
-// whereas the pattern "/" matches every path.
-//
-// 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.
-//
-// # Precedence
+// [METHOD ][HOST]/[PATH]
+//
+// All three parts are optional; "/" is a valid pattern.
+// If METHOD is present, it must be followed by at least one space or tab.
+//
+// Literal (that is, non-wildcard) parts of a pattern match
+// the corresponding parts of a request case-sensitively.
+//
+// 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.
+//
+// A pattern with no host matches every host.
+// A pattern with a host matches URLs on that host only.
+//
+// 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.
+//
+// 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 [Request.PathValue] with the wildcard's name.
+// A trailing slash in a path acts as an anonymous "..." wildcard.
+//
+// The special wildcard {$} matches only the end of the URL.
+// For example, the pattern "/{$}" matches only the path "/",
+// whereas the pattern "/" matches every path.
+//
+// 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.//
-// 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 to [ServeMux.Handle] or [ServeMux.HandleFunc] conflicts with
-// another pattern that is already registered, those functions panic.
-//
-// 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.
-//
-// 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.
-//
-// # Trailing-slash redirection
+// # Precedence
+//
+// 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 to [ServeMux.Handle] or [ServeMux.HandleFunc] conflicts with
+// another pattern that is already registered, those functions panic.
+//
+// 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.
+//
+// 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.//
-// Consider a [ServeMux] 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.
-//
-// # Request sanitizing
+// # Trailing-slash redirection
+//
+// Consider a [ServeMux] 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.//
-// 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.
-// Escaped path elements such as "%2e" for "." and "%2f" for "/" are preserved
-// and aren't considered separators for request routing.
-//
-// # Compatibility
+// # Request sanitizing
+//
+// 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.
+// Escaped path elements such as "%2e" for "." and "%2f" for "/" are preserved
+// and aren't considered separators for request routing.//
-// 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.
-//
-// The backwards-incompatible changes include:
-// - 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.
-// - 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 [ServeMux.Handle] and [ServeMux.HandleFunc] 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.
-// - 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).
-// - 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 https://go.dev/issue/21955 for details.
-typeServeMuxstruct {
-musync.RWMutex
-treeroutingNode
-indexroutingIndex
-mux121serveMux121// used only when GODEBUG=httpmuxgo121=1
-}
-
-// NewServeMux allocates and returns a new [ServeMux].
-func () *ServeMux {
-return &ServeMux{}
-}
-
-// DefaultServeMux is the default [ServeMux] used by [Serve].
-varDefaultServeMux = &defaultServeMux
-
-vardefaultServeMuxServeMux
+// # Compatibility
+//
+// 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.
+//
+// The backwards-incompatible changes include:
+// - 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.
+// - 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 [ServeMux.Handle] and [ServeMux.HandleFunc] 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.
+// - 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).
+// - 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 https://go.dev/issue/21955 for details.
+typeServeMuxstruct {
+musync.RWMutex
+treeroutingNode
+indexroutingIndex
+mux121serveMux121// used only when GODEBUG=httpmuxgo121=1
+}
+
+// NewServeMux allocates and returns a new [ServeMux].
+func () *ServeMux {
+return &ServeMux{}
+}
+
+// DefaultServeMux is the default [ServeMux] used by [Serve].
+varDefaultServeMux = &defaultServeMux
-// cleanPath returns the canonical path for p, eliminating . and .. elements.
-func ( string) string {
-if == "" {
-return"/"
- }
-if [0] != '/' {
- = "/" +
- }
- := path.Clean()
-// path.Clean removes trailing slash except for root;
- // put the trailing slash back if necessary.
-if [len()-1] == '/' && != "/" {
-// Fast path for common case of p being the string we want:
-iflen() == len()+1 && strings.HasPrefix(, ) {
- =
- } else {
- += "/"
- }
- }
-return
-}
-
-// stripHostPort returns h without any trailing ":<port>".
-func ( string) string {
-// If no port on host, return unchanged
-if !strings.Contains(, ":") {
-return
- }
- , , := net.SplitHostPort()
-if != nil {
-return// on error, return unchanged
- }
-return
-}
-
-// 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.
-//
-// The path and host are used unchanged for CONNECT requests.
+vardefaultServeMuxServeMux
+
+// cleanPath returns the canonical path for p, eliminating . and .. elements.
+func ( string) string {
+if == "" {
+return"/"
+ }
+if [0] != '/' {
+ = "/" +
+ }
+ := path.Clean()
+// path.Clean removes trailing slash except for root;
+ // put the trailing slash back if necessary.
+if [len()-1] == '/' && != "/" {
+// Fast path for common case of p being the string we want:
+iflen() == len()+1 && strings.HasPrefix(, ) {
+ =
+ } else {
+ += "/"
+ }
+ }
+return
+}
+
+// stripHostPort returns h without any trailing ":<port>".
+func ( string) string {
+// If no port on host, return unchanged
+if !strings.Contains(, ":") {
+return
+ }
+ , , := net.SplitHostPort()
+if != nil {
+return// on error, return unchanged
+ }
+return
+}
+
+// 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.//
-// 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.
-//
-// If there is no registered handler that applies to the request,
-// Handler returns a “page not found” or “method not supported”
-// handler and an empty pattern.
-//
-// Handler does not modify its argument. In particular, it does not
-// populate named path wildcards, so r.PathValue will always return
-// the empty string.
-func ( *ServeMux) ( *Request) ( Handler, string) {
-ifuse121 {
-return .mux121.findHandler()
- }
- , , , := .findHandler()
-return ,
-}
-
-// findHandler finds a handler for a request.
-// If there is a matching handler, it returns it and the pattern that matched.
-// Otherwise it returns a Redirect or NotFound handler with the path that would match
-// after the redirect.
-func ( *ServeMux) ( *Request) ( Handler, string, *pattern, []string) {
-var *routingNode
- := .URL.Host
- := .URL.EscapedPath()
- :=
-// CONNECT requests are not canonicalized.
-if .Method == "CONNECT" {
-// If r.URL.Path is /tree and its handler is not registered,
- // the /tree -> /tree/ redirect applies to CONNECT requests
- // but the path canonicalization does not.
- , , := .matchOrRedirect(, .Method, , .URL)
-if != nil {
-returnRedirectHandler(.String(), StatusTemporaryRedirect), .Path, nil, nil
- }
-// Redo the match, this time with r.Host instead of r.URL.Host.
- // Pass a nil URL to skip the trailing-slash redirect logic.
- , , _ = .matchOrRedirect(.Host, .Method, , nil)
- } else {
-// All other requests have any port stripped and path cleaned
- // before passing to mux.handler.
- = stripHostPort(.Host)
- = cleanPath()
-
-// If the given path is /tree and its handler is not registered,
- // redirect for /tree/.
-var *url.URL
- , , = .matchOrRedirect(, .Method, , .URL)
-if != nil {
-returnRedirectHandler(.String(), StatusTemporaryRedirect), .pattern.String(), nil, nil
- }
-if != {
-// Redirect to cleaned path.
- := ""
-if != nil {
- = .pattern.String()
- }
- := &url.URL{Path: , RawQuery: .URL.RawQuery}
-returnRedirectHandler(.String(), StatusTemporaryRedirect), , nil, nil
- }
- }
-if == nil {
-// We didn't find a match with the request method. To distinguish between
- // Not Found and Method Not Allowed, see if there is another pattern that
- // matches except for the method.
- := .matchingMethods(, )
-iflen() > 0 {
-returnHandlerFunc(func( ResponseWriter, *Request) {
- .Header().Set("Allow", strings.Join(, ", "))
-Error(, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
- }), "", nil, nil
- }
-returnNotFoundHandler(), "", nil, nil
- }
-return .handler, .pattern.String(), .pattern,
-}
-
-// matchOrRedirect looks up a node in the tree that matches the host, method and path.
-//
-// If the url argument is non-nil, handler also deals with trailing-slash
-// redirection: when a path doesn't match exactly, the match is tried again
-// after appending "/" to the path. If that second match succeeds, the last
-// return value is the URL to redirect to.
-func ( *ServeMux) (, , string, *url.URL) ( *routingNode, []string, *url.URL) {
- .mu.RLock()
-defer .mu.RUnlock()
-
- , := .tree.match(, , )
-// We can terminate here if any of the following is true:
- // - We have an exact match already.
- // - We were asked not to try trailing slash redirection.
- // - The URL already has a trailing slash.
- // - The URL is an empty string.
-if !exactMatch(, ) && != nil && !strings.HasSuffix(, "/") && != "" {
-// If there is an exact match with a trailing slash, then redirect.
- += "/"
- , := .tree.match(, , )
-ifexactMatch(, ) {
-// It is safe to return n2 here: it is used only in the second RedirectHandler case
- // of findHandler, and that method returns before it does the "n == nil" check where
- // the first return value matters. We return it here only to make the pattern available
- // to findHandler.
-return , nil, &url.URL{Path: cleanPath(.Path) + "/", RawQuery: .RawQuery}
- }
- }
-return , , nil
-}
-
-// exactMatch reports whether the node's pattern exactly matches the path.
-// As a special case, if the node is nil, exactMatch return false.
-//
-// Before wildcards were introduced, it was clear that an exact match meant
-// that the pattern and path were the same string. The only other possibility
-// was that a trailing-slash pattern, like "/", matched a path longer than
-// it, like "/a".
-//
-// With wildcards, we define an inexact match as any one where a multi wildcard
-// matches a non-empty string. All other matches are exact.
-// For example, these are all exact matches:
-//
-// pattern path
-// /a /a
-// /{x} /a
-// /a/{$} /a/
-// /a/ /a/
-//
-// The last case has a multi wildcard (implicitly), but the match is exact because
-// the wildcard matches the empty string.
-//
-// Examples of matches that are not exact:
+// The path and host are used unchanged for CONNECT requests.
+//
+// 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.
+//
+// If there is no registered handler that applies to the request,
+// Handler returns a “page not found” or “method not supported”
+// handler and an empty pattern.
+//
+// Handler does not modify its argument. In particular, it does not
+// populate named path wildcards, so r.PathValue will always return
+// the empty string.
+func ( *ServeMux) ( *Request) ( Handler, string) {
+ifuse121 {
+return .mux121.findHandler()
+ }
+ , , , := .findHandler()
+return ,
+}
+
+// findHandler finds a handler for a request.
+// If there is a matching handler, it returns it and the pattern that matched.
+// Otherwise it returns a Redirect or NotFound handler with the path that would match
+// after the redirect.
+func ( *ServeMux) ( *Request) ( Handler, string, *pattern, []string) {
+var *routingNode
+ := .URL.Host
+ := .URL.EscapedPath()
+ :=
+// CONNECT requests are not canonicalized.
+if .Method == "CONNECT" {
+// If r.URL.Path is /tree and its handler is not registered,
+ // the /tree -> /tree/ redirect applies to CONNECT requests
+ // but the path canonicalization does not.
+ , , := .matchOrRedirect(, .Method, , .URL)
+if != nil {
+returnRedirectHandler(.String(), StatusTemporaryRedirect), .Path, nil, nil
+ }
+// Redo the match, this time with r.Host instead of r.URL.Host.
+ // Pass a nil URL to skip the trailing-slash redirect logic.
+ , , _ = .matchOrRedirect(.Host, .Method, , nil)
+ } else {
+// All other requests have any port stripped and path cleaned
+ // before passing to mux.handler.
+ = stripHostPort(.Host)
+ = cleanPath()
+
+// If the given path is /tree and its handler is not registered,
+ // redirect for /tree/.
+var *url.URL
+ , , = .matchOrRedirect(, .Method, , .URL)
+if != nil {
+returnRedirectHandler(.String(), StatusTemporaryRedirect), .pattern.String(), nil, nil
+ }
+if != {
+// Redirect to cleaned path.
+ := ""
+if != nil {
+ = .pattern.String()
+ }
+ := &url.URL{Path: , RawQuery: .URL.RawQuery}
+returnRedirectHandler(.String(), StatusTemporaryRedirect), , nil, nil
+ }
+ }
+if == nil {
+// We didn't find a match with the request method. To distinguish between
+ // Not Found and Method Not Allowed, see if there is another pattern that
+ // matches except for the method.
+ := .matchingMethods(, )
+iflen() > 0 {
+returnHandlerFunc(func( ResponseWriter, *Request) {
+ .Header().Set("Allow", strings.Join(, ", "))
+Error(, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
+ }), "", nil, nil
+ }
+returnNotFoundHandler(), "", nil, nil
+ }
+return .handler, .pattern.String(), .pattern,
+}
+
+// matchOrRedirect looks up a node in the tree that matches the host, method and path.
+//
+// If the url argument is non-nil, handler also deals with trailing-slash
+// redirection: when a path doesn't match exactly, the match is tried again
+// after appending "/" to the path. If that second match succeeds, the last
+// return value is the URL to redirect to.
+func ( *ServeMux) (, , string, *url.URL) ( *routingNode, []string, *url.URL) {
+ .mu.RLock()
+defer .mu.RUnlock()
+
+ , := .tree.match(, , )
+// We can terminate here if any of the following is true:
+ // - We have an exact match already.
+ // - We were asked not to try trailing slash redirection.
+ // - The URL already has a trailing slash.
+ // - The URL is an empty string.
+if !exactMatch(, ) && != nil && !strings.HasSuffix(, "/") && != "" {
+// If there is an exact match with a trailing slash, then redirect.
+ += "/"
+ , := .tree.match(, , )
+ifexactMatch(, ) {
+// It is safe to return n2 here: it is used only in the second RedirectHandler case
+ // of findHandler, and that method returns before it does the "n == nil" check where
+ // the first return value matters. We return it here only to make the pattern available
+ // to findHandler.
+return , nil, &url.URL{Path: cleanPath(.Path) + "/", RawQuery: .RawQuery}
+ }
+ }
+return , , nil
+}
+
+// exactMatch reports whether the node's pattern exactly matches the path.
+// As a special case, if the node is nil, exactMatch return false.
+//
+// Before wildcards were introduced, it was clear that an exact match meant
+// that the pattern and path were the same string. The only other possibility
+// was that a trailing-slash pattern, like "/", matched a path longer than
+// it, like "/a".
+//
+// With wildcards, we define an inexact match as any one where a multi wildcard
+// matches a non-empty string. All other matches are exact.
+// For example, these are all exact matches:
+//
+// pattern path
+// /a /a
+// /{x} /a
+// /a/{$} /a/
+// /a/ /a/
+//
+// The last case has a multi wildcard (implicitly), but the match is exact because
+// the wildcard matches the empty string.//
-// pattern path
-// / /a
-// /a/{x...} /a/b
-func ( *routingNode, string) bool {
-if == nil {
-returnfalse
- }
-// We can't directly implement the definition (empty match for multi
- // wildcard) because we don't record a match for anonymous multis.
-
-// If there is no multi, the match is exact.
-if !.pattern.lastSegment().multi {
-returntrue
- }
-
-// If the path doesn't end in a trailing slash, then the multi match
- // is non-empty.
-iflen() > 0 && [len()-1] != '/' {
-returnfalse
- }
-// Only patterns ending in {$} or a multi wildcard can
- // match a path with a trailing slash.
- // For the match to be exact, the number of pattern
- // segments should be the same as the number of slashes in the path.
- // E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
-returnlen(.pattern.segments) == strings.Count(, "/")
-}
-
-// matchingMethods return a sorted list of all methods that would match with the given host and path.
-func ( *ServeMux) (, string) []string {
-// Hold the read lock for the entire method so that the two matches are done
- // on the same set of registered patterns.
- .mu.RLock()
-defer .mu.RUnlock()
- := map[string]bool{}
- .tree.matchingMethods(, , )
-// matchOrRedirect will try appending a trailing slash if there is no match.
-if !strings.HasSuffix(, "/") {
- .tree.matchingMethods(, +"/", )
- }
-returnslices.Sorted(maps.Keys())
-}
-
-// ServeHTTP dispatches the request to the handler whose
-// pattern most closely matches the request URL.
-func ( *ServeMux) ( ResponseWriter, *Request) {
-if .RequestURI == "*" {
-if .ProtoAtLeast(1, 1) {
- .Header().Set("Connection", "close")
- }
- .WriteHeader(StatusBadRequest)
-return
- }
-varHandler
-ifuse121 {
- , _ = .mux121.findHandler()
- } else {
- , .Pattern, .pat, .matches = .findHandler()
- }
- .ServeHTTP(, )
-}
-
-// The four functions below all call ServeMux.register so that callerLocation
-// always refers to user code.
-
-// Handle registers the handler for the given pattern.
-// If the given pattern conflicts with one that is already registered
-// or if the pattern is invalid, Handle panics.
-//
-// See [ServeMux] for details on valid patterns and conflict rules.
-func ( *ServeMux) ( string, Handler) {
-ifuse121 {
- .mux121.handle(, )
- } else {
- .register(, )
- }
-}
-
-// HandleFunc registers the handler function for the given pattern.
-// If the given pattern conflicts with one that is already registered
-// or if the pattern is invalid, HandleFunc panics.
-//
-// See [ServeMux] for details on valid patterns and conflict rules.
-func ( *ServeMux) ( string, func(ResponseWriter, *Request)) {
-ifuse121 {
- .mux121.handleFunc(, )
- } else {
- .register(, HandlerFunc())
- }
-}
-
-// Handle registers the handler for the given pattern in [DefaultServeMux].
-// The documentation for [ServeMux] explains how patterns are matched.
-func ( string, Handler) {
-ifuse121 {
-DefaultServeMux.mux121.handle(, )
- } else {
-DefaultServeMux.register(, )
- }
-}
-
-// HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
-// The documentation for [ServeMux] explains how patterns are matched.
-func ( string, func(ResponseWriter, *Request)) {
-ifuse121 {
-DefaultServeMux.mux121.handleFunc(, )
- } else {
-DefaultServeMux.register(, HandlerFunc())
- }
-}
-
-func ( *ServeMux) ( string, Handler) {
-if := .registerErr(, ); != nil {
-panic()
- }
-}
-
-func ( *ServeMux) ( string, Handler) error {
-if == "" {
-returnerrors.New("http: invalid pattern")
- }
-if == nil {
-returnerrors.New("http: nil handler")
- }
-if , := .(HandlerFunc); && == nil {
-returnerrors.New("http: nil handler")
- }
-
- , := parsePattern()
-if != nil {
-returnfmt.Errorf("parsing %q: %w", , )
- }
-
-// Get the caller's location, for better conflict error messages.
- // Skip register and whatever calls it.
- , , , := runtime.Caller(3)
-if ! {
- .loc = "unknown location"
- } else {
- .loc = fmt.Sprintf("%s:%d", , )
- }
-
- .mu.Lock()
-defer .mu.Unlock()
-// Check for conflict.
-if := .index.possiblyConflictingPatterns(, func( *pattern) error {
-if .conflictsWith() {
- := describeConflict(, )
-returnfmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
- , .loc, , .loc, )
- }
-returnnil
- }); != nil {
-return
- }
- .tree.addPattern(, )
- .index.addPattern()
-returnnil
-}
-
-// 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.
-//
-// The handler is typically nil, in which case [DefaultServeMux] is used.
+// Examples of matches that are not exact:
+//
+// pattern path
+// / /a
+// /a/{x...} /a/b
+func ( *routingNode, string) bool {
+if == nil {
+returnfalse
+ }
+// We can't directly implement the definition (empty match for multi
+ // wildcard) because we don't record a match for anonymous multis.
+
+// If there is no multi, the match is exact.
+if !.pattern.lastSegment().multi {
+returntrue
+ }
+
+// If the path doesn't end in a trailing slash, then the multi match
+ // is non-empty.
+iflen() > 0 && [len()-1] != '/' {
+returnfalse
+ }
+// Only patterns ending in {$} or a multi wildcard can
+ // match a path with a trailing slash.
+ // For the match to be exact, the number of pattern
+ // segments should be the same as the number of slashes in the path.
+ // E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
+returnlen(.pattern.segments) == strings.Count(, "/")
+}
+
+// matchingMethods return a sorted list of all methods that would match with the given host and path.
+func ( *ServeMux) (, string) []string {
+// Hold the read lock for the entire method so that the two matches are done
+ // on the same set of registered patterns.
+ .mu.RLock()
+defer .mu.RUnlock()
+ := map[string]bool{}
+ .tree.matchingMethods(, , )
+// matchOrRedirect will try appending a trailing slash if there is no match.
+if !strings.HasSuffix(, "/") {
+ .tree.matchingMethods(, +"/", )
+ }
+returnslices.Sorted(maps.Keys())
+}
+
+// ServeHTTP dispatches the request to the handler whose
+// pattern most closely matches the request URL.
+func ( *ServeMux) ( ResponseWriter, *Request) {
+if .RequestURI == "*" {
+if .ProtoAtLeast(1, 1) {
+ .Header().Set("Connection", "close")
+ }
+ .WriteHeader(StatusBadRequest)
+return
+ }
+varHandler
+ifuse121 {
+ , _ = .mux121.findHandler()
+ } else {
+ , .Pattern, .pat, .matches = .findHandler()
+ }
+ .ServeHTTP(, )
+}
+
+// The four functions below all call ServeMux.register so that callerLocation
+// always refers to user code.
+
+// Handle registers the handler for the given pattern.
+// If the given pattern conflicts with one that is already registered
+// or if the pattern is invalid, Handle panics.
+//
+// See [ServeMux] for details on valid patterns and conflict rules.
+func ( *ServeMux) ( string, Handler) {
+ifuse121 {
+ .mux121.handle(, )
+ } else {
+ .register(, )
+ }
+}
+
+// HandleFunc registers the handler function for the given pattern.
+// If the given pattern conflicts with one that is already registered
+// or if the pattern is invalid, HandleFunc panics.
+//
+// See [ServeMux] for details on valid patterns and conflict rules.
+func ( *ServeMux) ( string, func(ResponseWriter, *Request)) {
+ifuse121 {
+ .mux121.handleFunc(, )
+ } else {
+ .register(, HandlerFunc())
+ }
+}
+
+// Handle registers the handler for the given pattern in [DefaultServeMux].
+// The documentation for [ServeMux] explains how patterns are matched.
+func ( string, Handler) {
+ifuse121 {
+DefaultServeMux.mux121.handle(, )
+ } else {
+DefaultServeMux.register(, )
+ }
+}
+
+// HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
+// The documentation for [ServeMux] explains how patterns are matched.
+func ( string, func(ResponseWriter, *Request)) {
+ifuse121 {
+DefaultServeMux.mux121.handleFunc(, )
+ } else {
+DefaultServeMux.register(, HandlerFunc())
+ }
+}
+
+func ( *ServeMux) ( string, Handler) {
+if := .registerErr(, ); != nil {
+panic()
+ }
+}
+
+func ( *ServeMux) ( string, Handler) error {
+if == "" {
+returnerrors.New("http: invalid pattern")
+ }
+if == nil {
+returnerrors.New("http: nil handler")
+ }
+if , := .(HandlerFunc); && == nil {
+returnerrors.New("http: nil handler")
+ }
+
+ , := parsePattern()
+if != nil {
+returnfmt.Errorf("parsing %q: %w", , )
+ }
+
+// Get the caller's location, for better conflict error messages.
+ // Skip register and whatever calls it.
+ , , , := runtime.Caller(3)
+if ! {
+ .loc = "unknown location"
+ } else {
+ .loc = fmt.Sprintf("%s:%d", , )
+ }
+
+ .mu.Lock()
+defer .mu.Unlock()
+// Check for conflict.
+if := .index.possiblyConflictingPatterns(, func( *pattern) error {
+if .conflictsWith() {
+ := describeConflict(, )
+returnfmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
+ , .loc, , .loc, )
+ }
+returnnil
+ }); != nil {
+return
+ }
+ .tree.addPattern(, )
+ .index.addPattern()
+returnnil
+}
+
+// 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.//
-// HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
-// connections and they were configured with "h2" in the TLS
-// Config.NextProtos.
-//
-// Serve always returns a non-nil error.
-func ( net.Listener, Handler) error {
- := &Server{Handler: }
-return .Serve()
-}
-
-// 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.
-//
-// The handler is typically nil, in which case [DefaultServeMux] is used.
+// The handler is typically nil, in which case [DefaultServeMux] is used.
+//
+// HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
+// connections and they were configured with "h2" in the TLS
+// Config.NextProtos.
+//
+// Serve always returns a non-nil error.
+func ( net.Listener, Handler) error {
+ := &Server{Handler: }
+return .Serve()
+}
+
+// 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.//
-// 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.
-//
-// ServeTLS always returns a non-nil error.
-func ( net.Listener, Handler, , string) error {
- := &Server{Handler: }
-return .ServeTLS(, , )
-}
-
-// A Server defines parameters for running an HTTP server.
-// The zero value for Server is a valid configuration.
-typeServerstruct {
-// 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.
-Addrstring
-
-HandlerHandler// handler to invoke, http.DefaultServeMux if nil
+// The handler is typically nil, in which case [DefaultServeMux] is used.
+//
+// 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.
+//
+// ServeTLS always returns a non-nil error.
+func ( net.Listener, Handler, , string) error {
+ := &Server{Handler: }
+return .ServeTLS(, , )
+}
+
+// A Server defines parameters for running an HTTP server.
+// The zero value for Server is a valid configuration.
+typeServerstruct {
+// 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.
+Addrstring
-// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
- // otherwise responds with 200 OK and Content-Length: 0.
-DisableGeneralOptionsHandlerbool
-
-// 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.
-ReadTimeouttime.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 zero, the value of
- // ReadTimeout is used. If negative, or if zero and ReadTimeout
- // is zero or negative, there is no timeout.
-ReadHeaderTimeouttime.Duration
-
-// 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.
-WriteTimeouttime.Duration
-
-// IdleTimeout is the maximum amount of time to wait for the
- // next request when keep-alives are enabled. If zero, the value
- // of ReadTimeout is used. If negative, or if zero and ReadTimeout
- // is zero or negative, there is no timeout.
-IdleTimeouttime.Duration
-
-// 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.
-MaxHeaderBytesint
-
-// 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.
- //
- // Historically, TLSNextProto was used to disable HTTP/2 support.
- // The Server.Protocols field now provides a simpler way to do this.
-TLSNextProtomap[string]func(*Server, *tls.Conn, Handler)
-
-// ConnState specifies an optional callback function that is
- // called when a client connection changes state. See the
- // ConnState type and associated constants for details.
-ConnStatefunc(net.Conn, ConnState)
-
-// 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
-
-// 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.
-BaseContextfunc(net.Listener) context.Context
-
-// 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.
-ConnContextfunc(ctx context.Context, c net.Conn) context.Context
-
-// HTTP2 configures HTTP/2 connections.
-HTTP2 *HTTP2Config
-
-// Protocols is the set of protocols accepted by the server.
- //
- // If Protocols includes UnencryptedHTTP2, the server will accept
- // unencrypted HTTP/2 connections. The server can serve both
- // HTTP/1 and unencrypted HTTP/2 on the same address and port.
- //
- // If Protocols is nil, the default is usually HTTP/1 and HTTP/2.
- // If TLSNextProto is non-nil and does not contain an "h2" entry,
- // the default is HTTP/1 only.
-Protocols *Protocols
-
-inShutdownatomic.Bool// true when server is in shutdown
+HandlerHandler// 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.
+DisableGeneralOptionsHandlerbool
+
+// 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.
+ReadTimeouttime.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 zero, the value of
+ // ReadTimeout is used. If negative, or if zero and ReadTimeout
+ // is zero or negative, there is no timeout.
+ReadHeaderTimeouttime.Duration
+
+// 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.
+WriteTimeouttime.Duration
+
+// IdleTimeout is the maximum amount of time to wait for the
+ // next request when keep-alives are enabled. If zero, the value
+ // of ReadTimeout is used. If negative, or if zero and ReadTimeout
+ // is zero or negative, there is no timeout.
+IdleTimeouttime.Duration
+
+// 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.
+MaxHeaderBytesint
+
+// 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.
+ //
+ // Historically, TLSNextProto was used to disable HTTP/2 support.
+ // The Server.Protocols field now provides a simpler way to do this.
+TLSNextProtomap[string]func(*Server, *tls.Conn, Handler)
+
+// ConnState specifies an optional callback function that is
+ // called when a client connection changes state. See the
+ // ConnState type and associated constants for details.
+ConnStatefunc(net.Conn, ConnState)
+
+// 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
+
+// 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.
+BaseContextfunc(net.Listener) context.Context
+
+// 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.
+ConnContextfunc(ctx context.Context, c net.Conn) context.Context
+
+// HTTP2 configures HTTP/2 connections.
+HTTP2 *HTTP2Config
+
+// Protocols is the set of protocols accepted by the server.
+ //
+ // If Protocols includes UnencryptedHTTP2, the server will accept
+ // unencrypted HTTP/2 connections. The server can serve both
+ // HTTP/1 and unencrypted HTTP/2 on the same address and port.
+ //
+ // If Protocols is nil, the default is usually HTTP/1 and HTTP/2.
+ // If TLSNextProto is non-nil and does not contain an "h2" entry,
+ // the default is HTTP/1 only.
+Protocols *Protocols
-disableKeepAlivesatomic.Bool
-nextProtoOncesync.Once// guards setupHTTP2_* init
-nextProtoErrerror// result of http2.ConfigureServer if used
-
-musync.Mutex
-listenersmap[*net.Listener]struct{}
-activeConnmap[*conn]struct{}
-onShutdown []func()
-
-listenerGroupsync.WaitGroup
-}
-
-// Close immediately closes all active net.Listeners and any
-// connections in state [StateNew], [StateActive], or [StateIdle]. For a
-// graceful shutdown, use [Server.Shutdown].
-//
-// Close does not attempt to close (and does not even know about)
-// any hijacked connections, such as WebSockets.
-//
-// Close returns any error returned from closing the [Server]'s
-// underlying Listener(s).
-func ( *Server) () error {
- .inShutdown.Store(true)
- .mu.Lock()
-defer .mu.Unlock()
- := .closeListenersLocked()
-
-// Unlock s.mu while waiting for listenerGroup.
- // The group Add and Done calls are made with s.mu held,
- // to avoid adding a new listener in the window between
- // us setting inShutdown above and waiting here.
- .mu.Unlock()
- .listenerGroup.Wait()
- .mu.Lock()
-
-for := range .activeConn {
- .rwc.Close()
-delete(.activeConn, )
- }
-return
-}
-
-// shutdownPollIntervalMax is the max polling interval when checking
-// quiescence during Server.Shutdown. Polling starts with a small
-// interval and backs off to the max.
-// Ideally we could find a solution that doesn't involve polling,
-// but which also doesn't have a high runtime cost (and doesn't
-// involve any contentious mutexes), but that is left as an
-// exercise for the reader.
-constshutdownPollIntervalMax = 500 * time.Millisecond
-
-// 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 [Server]'s underlying Listener(s).
-//
-// When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and
-// [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the
-// program doesn't exit and waits instead for Shutdown to return.
-//
-// 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 [Server.RegisterOnShutdown] for a way to
-// register shutdown notification functions.
-//
-// Once Shutdown has been called on a server, it may not be reused;
-// future calls to methods such as Serve will return ErrServerClosed.
-func ( *Server) ( context.Context) error {
- .inShutdown.Store(true)
-
- .mu.Lock()
- := .closeListenersLocked()
-for , := range .onShutdown {
-go ()
- }
- .mu.Unlock()
- .listenerGroup.Wait()
-
- := time.Millisecond
- := func() time.Duration {
-// Add 10% jitter.
- := + time.Duration(rand.Intn(int(/10)))
-// Double and clamp for next time.
- *= 2
-if > shutdownPollIntervalMax {
- = shutdownPollIntervalMax
- }
-return
- }
-
- := time.NewTimer(())
-defer .Stop()
-for {
-if .closeIdleConns() {
-return
- }
-select {
-case<-.Done():
-return .Err()
-case<-.C:
- .Reset(())
- }
- }
-}
-
-// RegisterOnShutdown registers a function to call on [Server.Shutdown].
-// 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.
-func ( *Server) ( func()) {
- .mu.Lock()
- .onShutdown = append(.onShutdown, )
- .mu.Unlock()
-}
-
-// closeIdleConns closes all idle connections and reports whether the
-// server is quiescent.
-func ( *Server) () bool {
- .mu.Lock()
-defer .mu.Unlock()
- := true
-for := range .activeConn {
- , := .getState()
-// Issue 22682: treat StateNew connections as if
- // they're idle if we haven't read the first request's
- // header in over 5 seconds.
-if == StateNew && < time.Now().Unix()-5 {
- = StateIdle
- }
-if != StateIdle || == 0 {
-// Assume unixSec == 0 means it's a very new
- // connection, without state set yet.
- = false
-continue
- }
- .rwc.Close()
-delete(.activeConn, )
- }
-return
-}
-
-func ( *Server) () error {
-varerror
-for := range .listeners {
-if := (*).Close(); != nil && == nil {
- =
- }
- }
-return
-}
-
-// A ConnState represents the state of a client connection to a server.
-// It's used by the optional [Server.ConnState] hook.
-typeConnStateint
-
-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.
-StateNewConnState = 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
-)
-
-varstateName = map[ConnState]string{
-StateNew: "new",
-StateActive: "active",
-StateIdle: "idle",
-StateHijacked: "hijacked",
-StateClosed: "closed",
-}
-
-func ( ConnState) () string {
-returnstateName[]
-}
-
-// serverHandler delegates to either the server's Handler or
-// DefaultServeMux and also handles "OPTIONS *" requests.
-typeserverHandlerstruct {
-srv *Server
-}
-
-// ServeHTTP should be an internal detail,
-// but widely used packages access it using linkname.
-// Notable members of the hall of shame include:
-// - github.com/erda-project/erda-infra
-//
-// Do not remove or change the type signature.
-// See go.dev/issue/67401.
-//
-//go:linkname badServeHTTP net/http.serverHandler.ServeHTTP
-func ( serverHandler) ( ResponseWriter, *Request) {
- := .srv.Handler
-if == nil {
- = DefaultServeMux
- }
-if !.srv.DisableGeneralOptionsHandler && .RequestURI == "*" && .Method == "OPTIONS" {
- = globalOptionsHandler{}
- }
-
- .ServeHTTP(, )
-}
-
-func (serverHandler, ResponseWriter, *Request)
+inShutdownatomic.Bool// true when server is in shutdown
+
+disableKeepAlivesatomic.Bool
+nextProtoOncesync.Once// guards setupHTTP2_* init
+nextProtoErrerror// result of http2.ConfigureServer if used
+
+musync.Mutex
+listenersmap[*net.Listener]struct{}
+activeConnmap[*conn]struct{}
+onShutdown []func()
+
+listenerGroupsync.WaitGroup
+}
+
+// Close immediately closes all active net.Listeners and any
+// connections in state [StateNew], [StateActive], or [StateIdle]. For a
+// graceful shutdown, use [Server.Shutdown].
+//
+// Close does not attempt to close (and does not even know about)
+// any hijacked connections, such as WebSockets.
+//
+// Close returns any error returned from closing the [Server]'s
+// underlying Listener(s).
+func ( *Server) () error {
+ .inShutdown.Store(true)
+ .mu.Lock()
+defer .mu.Unlock()
+ := .closeListenersLocked()
+
+// Unlock s.mu while waiting for listenerGroup.
+ // The group Add and Done calls are made with s.mu held,
+ // to avoid adding a new listener in the window between
+ // us setting inShutdown above and waiting here.
+ .mu.Unlock()
+ .listenerGroup.Wait()
+ .mu.Lock()
+
+for := range .activeConn {
+ .rwc.Close()
+delete(.activeConn, )
+ }
+return
+}
+
+// shutdownPollIntervalMax is the max polling interval when checking
+// quiescence during Server.Shutdown. Polling starts with a small
+// interval and backs off to the max.
+// Ideally we could find a solution that doesn't involve polling,
+// but which also doesn't have a high runtime cost (and doesn't
+// involve any contentious mutexes), but that is left as an
+// exercise for the reader.
+constshutdownPollIntervalMax = 500 * time.Millisecond
+
+// 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 [Server]'s underlying Listener(s).
+//
+// When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and
+// [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the
+// program doesn't exit and waits instead for Shutdown to return.
+//
+// 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 [Server.RegisterOnShutdown] for a way to
+// register shutdown notification functions.
+//
+// Once Shutdown has been called on a server, it may not be reused;
+// future calls to methods such as Serve will return ErrServerClosed.
+func ( *Server) ( context.Context) error {
+ .inShutdown.Store(true)
+
+ .mu.Lock()
+ := .closeListenersLocked()
+for , := range .onShutdown {
+go ()
+ }
+ .mu.Unlock()
+ .listenerGroup.Wait()
+
+ := time.Millisecond
+ := func() time.Duration {
+// Add 10% jitter.
+ := + time.Duration(rand.Intn(int(/10)))
+// Double and clamp for next time.
+ *= 2
+if > shutdownPollIntervalMax {
+ = shutdownPollIntervalMax
+ }
+return
+ }
+
+ := time.NewTimer(())
+defer .Stop()
+for {
+if .closeIdleConns() {
+return
+ }
+select {
+case<-.Done():
+return .Err()
+case<-.C:
+ .Reset(())
+ }
+ }
+}
+
+// RegisterOnShutdown registers a function to call on [Server.Shutdown].
+// 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.
+func ( *Server) ( func()) {
+ .mu.Lock()
+ .onShutdown = append(.onShutdown, )
+ .mu.Unlock()
+}
+
+// closeIdleConns closes all idle connections and reports whether the
+// server is quiescent.
+func ( *Server) () bool {
+ .mu.Lock()
+defer .mu.Unlock()
+ := true
+for := range .activeConn {
+ , := .getState()
+// Issue 22682: treat StateNew connections as if
+ // they're idle if we haven't read the first request's
+ // header in over 5 seconds.
+if == StateNew && < time.Now().Unix()-5 {
+ = StateIdle
+ }
+if != StateIdle || == 0 {
+// Assume unixSec == 0 means it's a very new
+ // connection, without state set yet.
+ = false
+continue
+ }
+ .rwc.Close()
+delete(.activeConn, )
+ }
+return
+}
+
+func ( *Server) () error {
+varerror
+for := range .listeners {
+if := (*).Close(); != nil && == nil {
+ =
+ }
+ }
+return
+}
+
+// A ConnState represents the state of a client connection to a server.
+// It's used by the optional [Server.ConnState] hook.
+typeConnStateint
+
+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.
+StateNewConnState = 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
+)
+
+varstateName = map[ConnState]string{
+StateNew: "new",
+StateActive: "active",
+StateIdle: "idle",
+StateHijacked: "hijacked",
+StateClosed: "closed",
+}
+
+func ( ConnState) () string {
+returnstateName[]
+}
+
+// serverHandler delegates to either the server's Handler or
+// DefaultServeMux and also handles "OPTIONS *" requests.
+typeserverHandlerstruct {
+srv *Server
+}
+
+// ServeHTTP should be an internal detail,
+// but widely used packages access it using linkname.
+// Notable members of the hall of shame include:
+// - github.com/erda-project/erda-infra
+//
+// Do not remove or change the type signature.
+// See go.dev/issue/67401.
+//
+//go:linkname badServeHTTP net/http.serverHandler.ServeHTTP
+func ( serverHandler) ( ResponseWriter, *Request) {
+ := .srv.Handler
+if == nil {
+ = DefaultServeMux
+ }
+if !.srv.DisableGeneralOptionsHandler && .RequestURI == "*" && .Method == "OPTIONS" {
+ = globalOptionsHandler{}
+ }
+
+ .ServeHTTP(, )
+}
-// AllowQuerySemicolons returns a handler that serves requests by converting any
-// unescaped semicolons in the URL query to ampersands, and invoking the handler h.
-//
-// 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.
-//
-// AllowQuerySemicolons should be invoked before [Request.ParseForm] is called.
-func ( Handler) Handler {
-returnHandlerFunc(func( ResponseWriter, *Request) {
-ifstrings.Contains(.URL.RawQuery, ";") {
- := new(Request)
- * = *
- .URL = new(url.URL)
- *.URL = *.URL
- .URL.RawQuery = strings.ReplaceAll(.URL.RawQuery, ";", "&")
- .ServeHTTP(, )
- } else {
- .ServeHTTP(, )
- }
- })
-}
-
-// ListenAndServe listens on the TCP network address s.Addr and then
-// calls [Serve] to handle requests on incoming connections.
-// Accepted connections are configured to enable TCP keep-alives.
-//
-// If s.Addr is blank, ":http" is used.
+func (serverHandler, ResponseWriter, *Request)
+
+// AllowQuerySemicolons returns a handler that serves requests by converting any
+// unescaped semicolons in the URL query to ampersands, and invoking the handler h.
+//
+// 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.
+//
+// AllowQuerySemicolons should be invoked before [Request.ParseForm] is called.
+func ( Handler) Handler {
+returnHandlerFunc(func( ResponseWriter, *Request) {
+ifstrings.Contains(.URL.RawQuery, ";") {
+ := new(Request)
+ * = *
+ .URL = new(url.URL)
+ *.URL = *.URL
+ .URL.RawQuery = strings.ReplaceAll(.URL.RawQuery, ";", "&")
+ .ServeHTTP(, )
+ } else {
+ .ServeHTTP(, )
+ }
+ })
+}
+
+// ListenAndServe listens on the TCP network address s.Addr and then
+// calls [Serve] to handle requests on incoming connections.
+// Accepted connections are configured to enable TCP keep-alives.//
-// ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
-// the returned error is [ErrServerClosed].
-func ( *Server) () error {
-if .shuttingDown() {
-returnErrServerClosed
- }
- := .Addr
-if == "" {
- = ":http"
- }
- , := net.Listen("tcp", )
-if != nil {
-return
- }
-return .Serve()
-}
-
-vartestHookServerServefunc(*Server, net.Listener) // used if non-nil
+// If s.Addr is blank, ":http" is used.
+//
+// ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
+// the returned error is [ErrServerClosed].
+func ( *Server) () error {
+if .shuttingDown() {
+returnErrServerClosed
+ }
+ := .Addr
+if == "" {
+ = ":http"
+ }
+ , := net.Listen("tcp", )
+if != nil {
+return
+ }
+return .Serve()
+}
-// shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
-// automatic HTTP/2. (which sets up the s.TLSNextProto map)
-func ( *Server) () bool {
-if .TLSConfig == nil {
-// Compatibility with Go 1.6:
- // If there's no TLSConfig, it's possible that the user just
- // didn't set it on the http.Server, but did pass it to
- // tls.NewListener and passed that listener to Serve.
- // So we should configure HTTP/2 (to set up s.TLSNextProto)
- // in case the listener returns an "h2" *tls.Conn.
-returntrue
- }
-if .protocols().UnencryptedHTTP2() {
-returntrue
- }
-// The user specified a TLSConfig on their http.Server.
- // In this, case, only configure HTTP/2 if their tls.Config
- // explicitly mentions "h2". Otherwise http2.ConfigureServer
- // would modify the tls.Config to add it, but they probably already
- // passed this tls.Config to tls.NewListener. And if they did,
- // it's too late anyway to fix it. It would only be potentially racy.
- // See Issue 15908.
-returnslices.Contains(.TLSConfig.NextProtos, http2NextProtoTLS)
-}
-
-// ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
-// and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
-varErrServerClosed = errors.New("http: Server closed")
-
-// Serve accepts incoming connections on the Listener l, creating a
-// new service goroutine for each. The service goroutines read requests and
-// then call s.Handler to reply to them.
-//
-// HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
-// connections and they were configured with "h2" in the TLS
-// Config.NextProtos.
-//
-// Serve always returns a non-nil error and closes l.
-// After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
-func ( *Server) ( net.Listener) error {
-if := testHookServerServe; != nil {
- (, ) // call hook with unwrapped listener
- }
-
- :=
- = &onceCloseListener{Listener: }
-defer .Close()
-
-if := .setupHTTP2_Serve(); != nil {
-return
- }
-
-if !.trackListener(&, true) {
-returnErrServerClosed
- }
-defer .trackListener(&, false)
-
- := context.Background()
-if .BaseContext != nil {
- = .BaseContext()
-if == nil {
-panic("BaseContext returned a nil context")
- }
- }
-
-vartime.Duration// how long to sleep on accept failure
+vartestHookServerServefunc(*Server, net.Listener) // used if non-nil
+
+// shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
+// automatic HTTP/2. (which sets up the s.TLSNextProto map)
+func ( *Server) () bool {
+if .TLSConfig == nil {
+// Compatibility with Go 1.6:
+ // If there's no TLSConfig, it's possible that the user just
+ // didn't set it on the http.Server, but did pass it to
+ // tls.NewListener and passed that listener to Serve.
+ // So we should configure HTTP/2 (to set up s.TLSNextProto)
+ // in case the listener returns an "h2" *tls.Conn.
+returntrue
+ }
+if .protocols().UnencryptedHTTP2() {
+returntrue
+ }
+// The user specified a TLSConfig on their http.Server.
+ // In this, case, only configure HTTP/2 if their tls.Config
+ // explicitly mentions "h2". Otherwise http2.ConfigureServer
+ // would modify the tls.Config to add it, but they probably already
+ // passed this tls.Config to tls.NewListener. And if they did,
+ // it's too late anyway to fix it. It would only be potentially racy.
+ // See Issue 15908.
+returnslices.Contains(.TLSConfig.NextProtos, http2NextProtoTLS)
+}
+
+// ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
+// and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
+varErrServerClosed = errors.New("http: Server closed")
+
+// Serve accepts incoming connections on the Listener l, creating a
+// new service goroutine for each. The service goroutines read requests and
+// then call s.Handler to reply to them.
+//
+// HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
+// connections and they were configured with "h2" in the TLS
+// Config.NextProtos.
+//
+// Serve always returns a non-nil error and closes l.
+// After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
+func ( *Server) ( net.Listener) error {
+if := testHookServerServe; != nil {
+ (, ) // call hook with unwrapped listener
+ }
+
+ :=
+ = &onceCloseListener{Listener: }
+defer .Close()
+
+if := .setupHTTP2_Serve(); != nil {
+return
+ }
+
+if !.trackListener(&, true) {
+returnErrServerClosed
+ }
+defer .trackListener(&, false)
+
+ := context.Background()
+if .BaseContext != nil {
+ = .BaseContext()
+if == nil {
+panic("BaseContext returned a nil context")
+ }
+ }
- := context.WithValue(, ServerContextKey, )
-for {
- , := .Accept()
-if != nil {
-if .shuttingDown() {
-returnErrServerClosed
- }
-if , := .(net.Error); && .Temporary() {
-if == 0 {
- = 5 * time.Millisecond
- } else {
- *= 2
- }
-if := 1 * time.Second; > {
- =
- }
- .logf("http: Accept error: %v; retrying in %v", , )
-time.Sleep()
-continue
- }
-return
- }
- :=
-if := .ConnContext; != nil {
- = (, )
-if == nil {
-panic("ConnContext returned nil")
- }
- }
- = 0
- := .newConn()
- .setState(.rwc, StateNew, runHooks) // before Serve can return
-go .serve()
- }
-}
-
-// 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 s.Handler to reply to them.
-//
-// Files containing a certificate and matching private key for the
-// server must be provided if neither the [Server]'s
-// TLSConfig.Certificates, TLSConfig.GetCertificate nor
-// config.GetConfigForClient 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.
-//
-// ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
-// returned error is [ErrServerClosed].
-func ( *Server) ( net.Listener, , string) error {
-// Setup HTTP/2 before s.Serve, to initialize s.TLSConfig
- // before we clone it and create the TLS Listener.
-if := .setupHTTP2_ServeTLS(); != nil {
-return
- }
-
- := cloneTLSConfig(.TLSConfig)
- .NextProtos = adjustNextProtos(.NextProtos, .protocols())
-
- := len(.Certificates) > 0 || .GetCertificate != nil || .GetConfigForClient != nil
-if ! || != "" || != "" {
-varerror
- .Certificates = make([]tls.Certificate, 1)
- .Certificates[0], = tls.LoadX509KeyPair(, )
-if != nil {
-return
- }
- }
-
- := tls.NewListener(, )
-return .Serve()
-}
-
-func ( *Server) () Protocols {
-if .Protocols != nil {
-return *.Protocols// user-configured set
- }
-
-// The historic way of disabling HTTP/2 is to set TLSNextProto to
- // a non-nil map with no "h2" entry.
- , := .TLSNextProto["h2"]
- := .TLSNextProto != nil && !
-
-// If GODEBUG=http2server=0, then HTTP/2 is disabled unless
- // the user has manually added an "h2" entry to TLSNextProto
- // (probably by using x/net/http2 directly).
-ifhttp2server.Value() == "0" && ! {
- = true
- }
-
-varProtocols
- .SetHTTP1(true) // default always includes HTTP/1
-if ! {
- .SetHTTP2(true)
- }
-return
-}
-
-// adjustNextProtos adds or removes "http/1.1" and "h2" entries from
-// a tls.Config.NextProtos list, according to the set of protocols in protos.
-func ( []string, Protocols) []string {
-// Make a copy of NextProtos since it might be shared with some other tls.Config.
- // (tls.Config.Clone doesn't do a deep copy.)
- //
- // We could avoid an allocation in the common case by checking to see if the slice
- // is already in order, but this is just one small allocation per connection.
- = slices.Clone()
-varProtocols
- = slices.DeleteFunc(, func( string) bool {
-switch {
-case"http/1.1":
-if !.HTTP1() {
-returntrue
- }
- .SetHTTP1(true)
-case"h2":
-if !.HTTP2() {
-returntrue
- }
- .SetHTTP2(true)
- }
-returnfalse
- })
-if .HTTP2() && !.HTTP2() {
- = append(, "h2")
- }
-if .HTTP1() && !.HTTP1() {
- = append(, "http/1.1")
- }
-return
-}
-
-// trackListener adds or removes a net.Listener to the set of tracked
-// listeners.
-//
-// We store a pointer to interface in the map set, in case the
-// net.Listener is not comparable. This is safe because we only call
-// trackListener via Serve and can track+defer untrack the same
-// pointer to local variable there. We never need to compare a
-// Listener from another caller.
-//
-// It reports whether the server is still up (not Shutdown or Closed).
-func ( *Server) ( *net.Listener, bool) bool {
- .mu.Lock()
-defer .mu.Unlock()
-if .listeners == nil {
- .listeners = make(map[*net.Listener]struct{})
- }
-if {
-if .shuttingDown() {
-returnfalse
- }
- .listeners[] = struct{}{}
- .listenerGroup.Add(1)
- } else {
-delete(.listeners, )
- .listenerGroup.Done()
- }
-returntrue
-}
-
-func ( *Server) ( *conn, bool) {
- .mu.Lock()
-defer .mu.Unlock()
-if .activeConn == nil {
- .activeConn = make(map[*conn]struct{})
- }
-if {
- .activeConn[] = struct{}{}
- } else {
-delete(.activeConn, )
- }
-}
-
-func ( *Server) () time.Duration {
-if .IdleTimeout != 0 {
-return .IdleTimeout
- }
-return .ReadTimeout
-}
-
-func ( *Server) () time.Duration {
-if .ReadHeaderTimeout != 0 {
-return .ReadHeaderTimeout
- }
-return .ReadTimeout
-}
-
-func ( *Server) () bool {
-return !.disableKeepAlives.Load() && !.shuttingDown()
-}
-
-func ( *Server) () bool {
-return .inShutdown.Load()
-}
-
-// 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.
-func ( *Server) ( bool) {
-if {
- .disableKeepAlives.Store(false)
-return
- }
- .disableKeepAlives.Store(true)
-
-// Close idle HTTP/1 conns:
- .closeIdleConns()
-
-// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
-}
-
-func ( *Server) ( string, ...any) {
-if .ErrorLog != nil {
- .ErrorLog.Printf(, ...)
- } else {
-log.Printf(, ...)
- }
-}
-
-// logf prints to the ErrorLog of the *Server associated with request r
-// via ServerContextKey. If there's no associated server, or if ErrorLog
-// is nil, logging is done via the log package's standard logger.
-func ( *Request, string, ...any) {
- , := .Context().Value(ServerContextKey).(*Server)
-if != nil && .ErrorLog != nil {
- .ErrorLog.Printf(, ...)
- } else {
-log.Printf(, ...)
- }
-}
-
-// ListenAndServe listens on the TCP network address addr and then calls
-// [Serve] with handler to handle requests on incoming connections.
-// Accepted connections are configured to enable TCP keep-alives.
-//
-// The handler is typically nil, in which case [DefaultServeMux] is used.
+vartime.Duration// how long to sleep on accept failure
+
+ := context.WithValue(, ServerContextKey, )
+for {
+ , := .Accept()
+if != nil {
+if .shuttingDown() {
+returnErrServerClosed
+ }
+if , := .(net.Error); && .Temporary() {
+if == 0 {
+ = 5 * time.Millisecond
+ } else {
+ *= 2
+ }
+if := 1 * time.Second; > {
+ =
+ }
+ .logf("http: Accept error: %v; retrying in %v", , )
+time.Sleep()
+continue
+ }
+return
+ }
+ :=
+if := .ConnContext; != nil {
+ = (, )
+if == nil {
+panic("ConnContext returned nil")
+ }
+ }
+ = 0
+ := .newConn()
+ .setState(.rwc, StateNew, runHooks) // before Serve can return
+go .serve()
+ }
+}
+
+// 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 s.Handler to reply to them.
+//
+// Files containing a certificate and matching private key for the
+// server must be provided if neither the [Server]'s
+// TLSConfig.Certificates, TLSConfig.GetCertificate nor
+// config.GetConfigForClient 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.
+//
+// ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
+// returned error is [ErrServerClosed].
+func ( *Server) ( net.Listener, , string) error {
+// Setup HTTP/2 before s.Serve, to initialize s.TLSConfig
+ // before we clone it and create the TLS Listener.
+if := .setupHTTP2_ServeTLS(); != nil {
+return
+ }
+
+ := cloneTLSConfig(.TLSConfig)
+ .NextProtos = adjustNextProtos(.NextProtos, .protocols())
+
+ := len(.Certificates) > 0 || .GetCertificate != nil || .GetConfigForClient != nil
+if ! || != "" || != "" {
+varerror
+ .Certificates = make([]tls.Certificate, 1)
+ .Certificates[0], = tls.LoadX509KeyPair(, )
+if != nil {
+return
+ }
+ }
+
+ := tls.NewListener(, )
+return .Serve()
+}
+
+func ( *Server) () Protocols {
+if .Protocols != nil {
+return *.Protocols// user-configured set
+ }
+
+// The historic way of disabling HTTP/2 is to set TLSNextProto to
+ // a non-nil map with no "h2" entry.
+ , := .TLSNextProto["h2"]
+ := .TLSNextProto != nil && !
+
+// If GODEBUG=http2server=0, then HTTP/2 is disabled unless
+ // the user has manually added an "h2" entry to TLSNextProto
+ // (probably by using x/net/http2 directly).
+ifhttp2server.Value() == "0" && ! {
+ = true
+ }
+
+varProtocols
+ .SetHTTP1(true) // default always includes HTTP/1
+if ! {
+ .SetHTTP2(true)
+ }
+return
+}
+
+// adjustNextProtos adds or removes "http/1.1" and "h2" entries from
+// a tls.Config.NextProtos list, according to the set of protocols in protos.
+func ( []string, Protocols) []string {
+// Make a copy of NextProtos since it might be shared with some other tls.Config.
+ // (tls.Config.Clone doesn't do a deep copy.)
+ //
+ // We could avoid an allocation in the common case by checking to see if the slice
+ // is already in order, but this is just one small allocation per connection.
+ = slices.Clone()
+varProtocols
+ = slices.DeleteFunc(, func( string) bool {
+switch {
+case"http/1.1":
+if !.HTTP1() {
+returntrue
+ }
+ .SetHTTP1(true)
+case"h2":
+if !.HTTP2() {
+returntrue
+ }
+ .SetHTTP2(true)
+ }
+returnfalse
+ })
+if .HTTP2() && !.HTTP2() {
+ = append(, "h2")
+ }
+if .HTTP1() && !.HTTP1() {
+ = append(, "http/1.1")
+ }
+return
+}
+
+// trackListener adds or removes a net.Listener to the set of tracked
+// listeners.
+//
+// We store a pointer to interface in the map set, in case the
+// net.Listener is not comparable. This is safe because we only call
+// trackListener via Serve and can track+defer untrack the same
+// pointer to local variable there. We never need to compare a
+// Listener from another caller.
+//
+// It reports whether the server is still up (not Shutdown or Closed).
+func ( *Server) ( *net.Listener, bool) bool {
+ .mu.Lock()
+defer .mu.Unlock()
+if .listeners == nil {
+ .listeners = make(map[*net.Listener]struct{})
+ }
+if {
+if .shuttingDown() {
+returnfalse
+ }
+ .listeners[] = struct{}{}
+ .listenerGroup.Add(1)
+ } else {
+delete(.listeners, )
+ .listenerGroup.Done()
+ }
+returntrue
+}
+
+func ( *Server) ( *conn, bool) {
+ .mu.Lock()
+defer .mu.Unlock()
+if .activeConn == nil {
+ .activeConn = make(map[*conn]struct{})
+ }
+if {
+ .activeConn[] = struct{}{}
+ } else {
+delete(.activeConn, )
+ }
+}
+
+func ( *Server) () time.Duration {
+if .IdleTimeout != 0 {
+return .IdleTimeout
+ }
+return .ReadTimeout
+}
+
+func ( *Server) () time.Duration {
+if .ReadHeaderTimeout != 0 {
+return .ReadHeaderTimeout
+ }
+return .ReadTimeout
+}
+
+func ( *Server) () bool {
+return !.disableKeepAlives.Load() && !.shuttingDown()
+}
+
+func ( *Server) () bool {
+return .inShutdown.Load()
+}
+
+// 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.
+func ( *Server) ( bool) {
+if {
+ .disableKeepAlives.Store(false)
+return
+ }
+ .disableKeepAlives.Store(true)
+
+// Close idle HTTP/1 conns:
+ .closeIdleConns()
+
+// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
+}
+
+func ( *Server) ( string, ...any) {
+if .ErrorLog != nil {
+ .ErrorLog.Printf(, ...)
+ } else {
+log.Printf(, ...)
+ }
+}
+
+// logf prints to the ErrorLog of the *Server associated with request r
+// via ServerContextKey. If there's no associated server, or if ErrorLog
+// is nil, logging is done via the log package's standard logger.
+func ( *Request, string, ...any) {
+ , := .Context().Value(ServerContextKey).(*Server)
+if != nil && .ErrorLog != nil {
+ .ErrorLog.Printf(, ...)
+ } else {
+log.Printf(, ...)
+ }
+}
+
+// ListenAndServe listens on the TCP network address addr and then calls
+// [Serve] with handler to handle requests on incoming connections.
+// Accepted connections are configured to enable TCP keep-alives.//
-// ListenAndServe always returns a non-nil error.
-func ( string, Handler) error {
- := &Server{Addr: , Handler: }
-return .ListenAndServe()
-}
-
-// ListenAndServeTLS acts identically to [ListenAndServe], 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.
-func (, , string, Handler) error {
- := &Server{Addr: , Handler: }
-return .ListenAndServeTLS(, )
-}
-
-// ListenAndServeTLS listens on the TCP network address s.Addr and
-// then calls [ServeTLS] to handle requests on incoming TLS connections.
-// Accepted connections are configured to enable TCP keep-alives.
-//
-// Filenames containing a certificate and matching private key for the
-// server must be provided if neither the [Server]'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.
-//
-// If s.Addr is blank, ":https" is used.
+// The handler is typically nil, in which case [DefaultServeMux] is used.
+//
+// ListenAndServe always returns a non-nil error.
+func ( string, Handler) error {
+ := &Server{Addr: , Handler: }
+return .ListenAndServe()
+}
+
+// ListenAndServeTLS acts identically to [ListenAndServe], 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.
+func (, , string, Handler) error {
+ := &Server{Addr: , Handler: }
+return .ListenAndServeTLS(, )
+}
+
+// ListenAndServeTLS listens on the TCP network address s.Addr and
+// then calls [ServeTLS] to handle requests on incoming TLS connections.
+// Accepted connections are configured to enable TCP keep-alives.
+//
+// Filenames containing a certificate and matching private key for the
+// server must be provided if neither the [Server]'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.//
-// ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
-// [Server.Close], the returned error is [ErrServerClosed].
-func ( *Server) (, string) error {
-if .shuttingDown() {
-returnErrServerClosed
- }
- := .Addr
-if == "" {
- = ":https"
- }
-
- , := net.Listen("tcp", )
-if != nil {
-return
- }
-
-defer .Close()
+// If s.Addr is blank, ":https" is used.
+//
+// ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
+// [Server.Close], the returned error is [ErrServerClosed].
+func ( *Server) (, string) error {
+if .shuttingDown() {
+returnErrServerClosed
+ }
+ := .Addr
+if == "" {
+ = ":https"
+ }
+
+ , := net.Listen("tcp", )
+if != nil {
+return
+ }
-return .ServeTLS(, , )
-}
-
-// setupHTTP2_ServeTLS conditionally configures HTTP/2 on
-// s and reports whether there was an error setting it up. If it is
-// not configured for policy reasons, nil is returned.
-func ( *Server) () error {
- .nextProtoOnce.Do(.onceSetNextProtoDefaults)
-return .nextProtoErr
-}
-
-// setupHTTP2_Serve is called from (*Server).Serve and conditionally
-// configures HTTP/2 on s using a more conservative policy than
-// setupHTTP2_ServeTLS because Serve is called after tls.Listen,
-// and may be called concurrently. See shouldConfigureHTTP2ForServe.
-//
-// The tests named TestTransportAutomaticHTTP2* and
-// TestConcurrentServerServe in server_test.go demonstrate some
-// of the supported use cases and motivations.
-func ( *Server) () error {
- .nextProtoOnce.Do(.onceSetNextProtoDefaults_Serve)
-return .nextProtoErr
-}
-
-func ( *Server) () {
-if .shouldConfigureHTTP2ForServe() {
- .onceSetNextProtoDefaults()
- }
-}
-
-varhttp2server = godebug.New("http2server")
+defer .Close()
+
+return .ServeTLS(, , )
+}
+
+// setupHTTP2_ServeTLS conditionally configures HTTP/2 on
+// s and reports whether there was an error setting it up. If it is
+// not configured for policy reasons, nil is returned.
+func ( *Server) () error {
+ .nextProtoOnce.Do(.onceSetNextProtoDefaults)
+return .nextProtoErr
+}
+
+// setupHTTP2_Serve is called from (*Server).Serve and conditionally
+// configures HTTP/2 on s using a more conservative policy than
+// setupHTTP2_ServeTLS because Serve is called after tls.Listen,
+// and may be called concurrently. See shouldConfigureHTTP2ForServe.
+//
+// The tests named TestTransportAutomaticHTTP2* and
+// TestConcurrentServerServe in server_test.go demonstrate some
+// of the supported use cases and motivations.
+func ( *Server) () error {
+ .nextProtoOnce.Do(.onceSetNextProtoDefaults_Serve)
+return .nextProtoErr
+}
+
+func ( *Server) () {
+if .shouldConfigureHTTP2ForServe() {
+ .onceSetNextProtoDefaults()
+ }
+}
-// onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
-// configured otherwise. (by setting s.TLSNextProto non-nil)
-// It must only be called via s.nextProtoOnce (use s.setupHTTP2_*).
-func ( *Server) () {
-ifomitBundledHTTP2 {
-return
- }
- := .protocols()
-if !.HTTP2() && !.UnencryptedHTTP2() {
-return
- }
-ifhttp2server.Value() == "0" {
-http2server.IncNonDefault()
-return
- }
-if , := .TLSNextProto["h2"]; {
-// TLSNextProto already contains an HTTP/2 implementation.
- // The user probably called golang.org/x/net/http2.ConfigureServer
- // to add it.
-return
- }
- := &http2Server{}
- .nextProtoErr = http2ConfigureServer(, )
-}
-
-// TimeoutHandler returns a [Handler] that runs h with the given time limit.
-//
-// 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 [ResponseWriter] will return
-// [ErrHandlerTimeout].
-//
-// TimeoutHandler supports the [Pusher] interface but does not support
-// the [Hijacker] or [Flusher] interfaces.
-func ( Handler, time.Duration, string) Handler {
-return &timeoutHandler{
-handler: ,
-body: ,
-dt: ,
- }
-}
-
-// ErrHandlerTimeout is returned on [ResponseWriter] Write calls
-// in handlers which have timed out.
-varErrHandlerTimeout = errors.New("http: Handler timeout")
-
-typetimeoutHandlerstruct {
-handlerHandler
-bodystring
-dttime.Duration
-
-// When set, no context will be created and this context will
- // be used instead.
-testContextcontext.Context
-}
-
-func ( *timeoutHandler) () string {
-if .body != "" {
-return .body
- }
-return"<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
-}
-
-func ( *timeoutHandler) ( ResponseWriter, *Request) {
- := .testContext
-if == nil {
-varcontext.CancelFunc
- , = context.WithTimeout(.Context(), .dt)
-defer ()
- }
- = .WithContext()
- := make(chanstruct{})
- := &timeoutWriter{
-w: ,
-h: make(Header),
-req: ,
- }
- := make(chanany, 1)
-gofunc() {
-deferfunc() {
-if := recover(); != nil {
- <-
- }
- }()
- .handler.ServeHTTP(, )
-close()
- }()
-select {
-case := <-:
-panic()
-case<-:
- .mu.Lock()
-defer .mu.Unlock()
- := .Header()
-maps.Copy(, .h)
-if !.wroteHeader {
- .code = StatusOK
- }
- .WriteHeader(.code)
- .Write(.wbuf.Bytes())
-case<-.Done():
- .mu.Lock()
-defer .mu.Unlock()
-switch := .Err(); {
-casecontext.DeadlineExceeded:
- .WriteHeader(StatusServiceUnavailable)
-io.WriteString(, .errorBody())
- .err = ErrHandlerTimeout
-default:
- .WriteHeader(StatusServiceUnavailable)
- .err =
- }
- }
-}
-
-typetimeoutWriterstruct {
-wResponseWriter
-hHeader
-wbufbytes.Buffer
-req *Request
-
-musync.Mutex
-errerror
-wroteHeaderbool
-codeint
-}
-
-var _ Pusher = (*timeoutWriter)(nil)
+varhttp2server = godebug.New("http2server")
+
+// onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
+// configured otherwise. (by setting s.TLSNextProto non-nil)
+// It must only be called via s.nextProtoOnce (use s.setupHTTP2_*).
+func ( *Server) () {
+ifomitBundledHTTP2 {
+return
+ }
+ := .protocols()
+if !.HTTP2() && !.UnencryptedHTTP2() {
+return
+ }
+ifhttp2server.Value() == "0" {
+http2server.IncNonDefault()
+return
+ }
+if , := .TLSNextProto["h2"]; {
+// TLSNextProto already contains an HTTP/2 implementation.
+ // The user probably called golang.org/x/net/http2.ConfigureServer
+ // to add it.
+return
+ }
+ := &http2Server{}
+ .nextProtoErr = http2ConfigureServer(, )
+}
+
+// TimeoutHandler returns a [Handler] that runs h with the given time limit.
+//
+// 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 [ResponseWriter] will return
+// [ErrHandlerTimeout].
+//
+// TimeoutHandler supports the [Pusher] interface but does not support
+// the [Hijacker] or [Flusher] interfaces.
+func ( Handler, time.Duration, string) Handler {
+return &timeoutHandler{
+handler: ,
+body: ,
+dt: ,
+ }
+}
+
+// ErrHandlerTimeout is returned on [ResponseWriter] Write calls
+// in handlers which have timed out.
+varErrHandlerTimeout = errors.New("http: Handler timeout")
+
+typetimeoutHandlerstruct {
+handlerHandler
+bodystring
+dttime.Duration
+
+// When set, no context will be created and this context will
+ // be used instead.
+testContextcontext.Context
+}
+
+func ( *timeoutHandler) () string {
+if .body != "" {
+return .body
+ }
+return"<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
+}
+
+func ( *timeoutHandler) ( ResponseWriter, *Request) {
+ := .testContext
+if == nil {
+varcontext.CancelFunc
+ , = context.WithTimeout(.Context(), .dt)
+defer ()
+ }
+ = .WithContext()
+ := make(chanstruct{})
+ := &timeoutWriter{
+w: ,
+h: make(Header),
+req: ,
+ }
+ := make(chanany, 1)
+gofunc() {
+deferfunc() {
+if := recover(); != nil {
+ <-
+ }
+ }()
+ .handler.ServeHTTP(, )
+close()
+ }()
+select {
+case := <-:
+panic()
+case<-:
+ .mu.Lock()
+defer .mu.Unlock()
+ := .Header()
+maps.Copy(, .h)
+if !.wroteHeader {
+ .code = StatusOK
+ }
+ .WriteHeader(.code)
+ .Write(.wbuf.Bytes())
+case<-.Done():
+ .mu.Lock()
+defer .mu.Unlock()
+switch := .Err(); {
+casecontext.DeadlineExceeded:
+ .WriteHeader(StatusServiceUnavailable)
+io.WriteString(, .errorBody())
+ .err = ErrHandlerTimeout
+default:
+ .WriteHeader(StatusServiceUnavailable)
+ .err =
+ }
+ }
+}
+
+typetimeoutWriterstruct {
+wResponseWriter
+hHeader
+wbufbytes.Buffer
+req *Request
+
+musync.Mutex
+errerror
+wroteHeaderbool
+codeint
+}
-// Push implements the [Pusher] interface.
-func ( *timeoutWriter) ( string, *PushOptions) error {
-if , := .w.(Pusher); {
-return .Push(, )
- }
-returnErrNotSupported
-}
-
-func ( *timeoutWriter) () Header { return .h }
+var _ Pusher = (*timeoutWriter)(nil)
+
+// Push implements the [Pusher] interface.
+func ( *timeoutWriter) ( string, *PushOptions) error {
+if , := .w.(Pusher); {
+return .Push(, )
+ }
+returnErrNotSupported
+}
-func ( *timeoutWriter) ( []byte) (int, error) {
- .mu.Lock()
-defer .mu.Unlock()
-if .err != nil {
-return0, .err
- }
-if !.wroteHeader {
- .writeHeaderLocked(StatusOK)
- }
-return .wbuf.Write()
-}
-
-func ( *timeoutWriter) ( int) {
-checkWriteHeaderCode()
-
-switch {
-case .err != nil:
-return
-case .wroteHeader:
-if .req != nil {
- := relevantCaller()
-logf(.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", .Function, path.Base(.File), .Line)
- }
-default:
- .wroteHeader = true
- .code =
- }
-}
-
-func ( *timeoutWriter) ( int) {
- .mu.Lock()
-defer .mu.Unlock()
- .writeHeaderLocked()
-}
-
-// onceCloseListener wraps a net.Listener, protecting it from
-// multiple Close calls.
-typeonceCloseListenerstruct {
-net.Listener
-oncesync.Once
-closeErrerror
-}
-
-func ( *onceCloseListener) () error {
- .once.Do(.close)
-return .closeErr
-}
-
-func ( *onceCloseListener) () { .closeErr = .Listener.Close() }
+func ( *timeoutWriter) () Header { return .h }
+
+func ( *timeoutWriter) ( []byte) (int, error) {
+ .mu.Lock()
+defer .mu.Unlock()
+if .err != nil {
+return0, .err
+ }
+if !.wroteHeader {
+ .writeHeaderLocked(StatusOK)
+ }
+return .wbuf.Write()
+}
+
+func ( *timeoutWriter) ( int) {
+checkWriteHeaderCode()
+
+switch {
+case .err != nil:
+return
+case .wroteHeader:
+if .req != nil {
+ := relevantCaller()
+logf(.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", .Function, path.Base(.File), .Line)
+ }
+default:
+ .wroteHeader = true
+ .code =
+ }
+}
+
+func ( *timeoutWriter) ( int) {
+ .mu.Lock()
+defer .mu.Unlock()
+ .writeHeaderLocked()
+}
+
+// onceCloseListener wraps a net.Listener, protecting it from
+// multiple Close calls.
+typeonceCloseListenerstruct {
+net.Listener
+oncesync.Once
+closeErrerror
+}
+
+func ( *onceCloseListener) () error {
+ .once.Do(.close)
+return .closeErr
+}
-// globalOptionsHandler responds to "OPTIONS *" requests.
-typeglobalOptionsHandlerstruct{}
-
-func (globalOptionsHandler) ( ResponseWriter, *Request) {
- .Header().Set("Content-Length", "0")
-if .ContentLength != 0 {
-// Read up to 4KB of OPTIONS body (as mentioned in the
- // spec as being reserved for future use), but anything
- // over that is considered a waste of server resources
- // (or an attack) and we abort and close the connection,
- // courtesy of MaxBytesReader's EOF behavior.
- := MaxBytesReader(, .Body, 4<<10)
-io.Copy(io.Discard, )
- }
-}
-
-// initALPNRequest is an HTTP handler that initializes certain
-// uninitialized fields in its *Request. Such partially-initialized
-// Requests come from ALPN protocol handlers.
-typeinitALPNRequeststruct {
-ctxcontext.Context
-c *tls.Conn
-hserverHandler
-}
-
-// BaseContext is an exported but unadvertised [http.Handler] method
-// recognized by x/net/http2 to pass down a context; the TLSNextProto
-// API predates context support so we shoehorn through the only
-// interface we have available.
-func ( initALPNRequest) () context.Context { return .ctx }
-
-func ( initALPNRequest) ( ResponseWriter, *Request) {
-if .TLS == nil {
- .TLS = &tls.ConnectionState{}
- *.TLS = .c.ConnectionState()
- }
-if .Body == nil {
- .Body = NoBody
- }
-if .RemoteAddr == "" {
- .RemoteAddr = .c.RemoteAddr().String()
- }
- .h.ServeHTTP(, )
-}
-
-// loggingConn is used for debugging.
-typeloggingConnstruct {
-namestring
-net.Conn
-}
-
-var (
-uniqNameMusync.Mutex
-uniqNameNext = make(map[string]int)
-)
-
-func ( string, net.Conn) net.Conn {
-uniqNameMu.Lock()
-deferuniqNameMu.Unlock()
-uniqNameNext[]++
-return &loggingConn{
-name: fmt.Sprintf("%s-%d", , uniqNameNext[]),
-Conn: ,
- }
-}
-
-func ( *loggingConn) ( []byte) ( int, error) {
-log.Printf("%s.Write(%d) = ....", .name, len())
- , = .Conn.Write()
-log.Printf("%s.Write(%d) = %d, %v", .name, len(), , )
-return
-}
-
-func ( *loggingConn) ( []byte) ( int, error) {
-log.Printf("%s.Read(%d) = ....", .name, len())
- , = .Conn.Read()
-log.Printf("%s.Read(%d) = %d, %v", .name, len(), , )
-return
-}
-
-func ( *loggingConn) () ( error) {
-log.Printf("%s.Close() = ...", .name)
- = .Conn.Close()
-log.Printf("%s.Close() = %v", .name, )
-return
-}
-
-// checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
-// It only contains one field (and a pointer field at that), so it
-// fits in an interface value without an extra allocation.
-typecheckConnErrorWriterstruct {
-c *conn
-}
-
-func ( checkConnErrorWriter) ( []byte) ( int, error) {
- , = .c.rwc.Write()
-if != nil && .c.werr == nil {
- .c.werr =
- .c.cancelCtx()
- }
-return
-}
-
-func ( []byte) ( int) {
-for , := range {
-if == '\r' || == '\n' {
- ++
-continue
- }
-break
- }
-return
-}
-
-// tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
-// looks like it might've been a misdirected plaintext HTTP request.
-func ( [5]byte) bool {
-switchstring([:]) {
-case"GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
-returntrue
- }
-returnfalse
-}
-
-// MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
-func ( Handler, int64) Handler {
-returnHandlerFunc(func( ResponseWriter, *Request) {
- := *
- .Body = MaxBytesReader(, .Body, )
- .ServeHTTP(, &)
- })
-}
+func ( *onceCloseListener) () { .closeErr = .Listener.Close() }
+
+// globalOptionsHandler responds to "OPTIONS *" requests.
+typeglobalOptionsHandlerstruct{}
+
+func (globalOptionsHandler) ( ResponseWriter, *Request) {
+ .Header().Set("Content-Length", "0")
+if .ContentLength != 0 {
+// Read up to 4KB of OPTIONS body (as mentioned in the
+ // spec as being reserved for future use), but anything
+ // over that is considered a waste of server resources
+ // (or an attack) and we abort and close the connection,
+ // courtesy of MaxBytesReader's EOF behavior.
+ := MaxBytesReader(, .Body, 4<<10)
+io.Copy(io.Discard, )
+ }
+}
+
+// initALPNRequest is an HTTP handler that initializes certain
+// uninitialized fields in its *Request. Such partially-initialized
+// Requests come from ALPN protocol handlers.
+typeinitALPNRequeststruct {
+ctxcontext.Context
+c *tls.Conn
+hserverHandler
+}
+
+// BaseContext is an exported but unadvertised [http.Handler] method
+// recognized by x/net/http2 to pass down a context; the TLSNextProto
+// API predates context support so we shoehorn through the only
+// interface we have available.
+func ( initALPNRequest) () context.Context { return .ctx }
+
+func ( initALPNRequest) ( ResponseWriter, *Request) {
+if .TLS == nil {
+ .TLS = &tls.ConnectionState{}
+ *.TLS = .c.ConnectionState()
+ }
+if .Body == nil {
+ .Body = NoBody
+ }
+if .RemoteAddr == "" {
+ .RemoteAddr = .c.RemoteAddr().String()
+ }
+ .h.ServeHTTP(, )
+}
+
+// loggingConn is used for debugging.
+typeloggingConnstruct {
+namestring
+net.Conn
+}
+
+var (
+uniqNameMusync.Mutex
+uniqNameNext = make(map[string]int)
+)
+
+func ( string, net.Conn) net.Conn {
+uniqNameMu.Lock()
+deferuniqNameMu.Unlock()
+uniqNameNext[]++
+return &loggingConn{
+name: fmt.Sprintf("%s-%d", , uniqNameNext[]),
+Conn: ,
+ }
+}
+
+func ( *loggingConn) ( []byte) ( int, error) {
+log.Printf("%s.Write(%d) = ....", .name, len())
+ , = .Conn.Write()
+log.Printf("%s.Write(%d) = %d, %v", .name, len(), , )
+return
+}
+
+func ( *loggingConn) ( []byte) ( int, error) {
+log.Printf("%s.Read(%d) = ....", .name, len())
+ , = .Conn.Read()
+log.Printf("%s.Read(%d) = %d, %v", .name, len(), , )
+return
+}
+
+func ( *loggingConn) () ( error) {
+log.Printf("%s.Close() = ...", .name)
+ = .Conn.Close()
+log.Printf("%s.Close() = %v", .name, )
+return
+}
+
+// checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
+// It only contains one field (and a pointer field at that), so it
+// fits in an interface value without an extra allocation.
+typecheckConnErrorWriterstruct {
+c *conn
+}
+
+func ( checkConnErrorWriter) ( []byte) ( int, error) {
+ , = .c.rwc.Write()
+if != nil && .c.werr == nil {
+ .c.werr =
+ .c.cancelCtx()
+ }
+return
+}
+
+func ( []byte) ( int) {
+for , := range {
+if == '\r' || == '\n' {
+ ++
+continue
+ }
+break
+ }
+return
+}
+
+// tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
+// looks like it might've been a misdirected plaintext HTTP request.
+func ( [5]byte) bool {
+switchstring([:]) {
+case"GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
+returntrue
+ }
+returnfalse
+}
+
+// MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
+func ( Handler, int64) Handler {
+returnHandlerFunc(func( ResponseWriter, *Request) {
+ := *
+ .Body = MaxBytesReader(, .Body, )
+ .ServeHTTP(, &)
+ })
+}
The pages are generated with Goldsv0.8.5. (GOOS=linux GOARCH=amd64)
diff --git a/src/net/http/transport.go.html b/src/net/http/transport.go.html
index e30ca670714..2461b992032 100644
--- a/src/net/http/transport.go.html
+++ b/src/net/http/transport.go.html
@@ -1780,7 +1780,7 @@
// // http2configureTransport will have already set NextProtos, but adjust it again // here to remove HTTP/1.1 if the user has disabled it.
- .TLSClientConfig.NextProtos = adjustNextProtos(.TLSClientConfig.NextProtos, )
+ .TLSClientConfig.NextProtos = adjustNextProtos(.TLSClientConfig.NextProtos, )}func ( *Transport) () Protocols {
diff --git a/src/runtime/cgo/cgo.go.html b/src/runtime/cgo/cgo.go.html
index dab931ec8bf..5121a320735 100644
--- a/src/runtime/cgo/cgo.go.html
+++ b/src/runtime/cgo/cgo.go.html
@@ -26,7 +26,7 @@
// Code generated by cmd/cgo; DO NOT EDIT.
-//line /opt/hostedtoolcache/go/1.26.6/x64/src/runtime/cgo/cgo.go:1:1
+//line /opt/hostedtoolcache/go/1.26.7/x64/src/runtime/cgo/cgo.go:1:1// Copyright 2010 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
diff --git a/statistics.html b/statistics.html
index 3fbc07ad838..ac128a9948e 100644
--- a/statistics.html
+++ b/statistics.html
@@ -13,7 +13,7 @@
Packages
Total 306 packages, 196 of them are standard packages.
Total 4900 source files, 4810 of them are Go source files.
- Total 1595771 lines of Go code.
+ Total 1595773 lines of Go code.
Averagely,
- each Go source file imports 7.18 packages and contains 332 lines of code.
- each package depends 6.70 other packages and contains 15.72 source files.
diff --git a/use/bufio..ReadWriter.html b/use/bufio..ReadWriter.html
index 886599a28af..affa23f3ba0 100644
--- a/use/bufio..ReadWriter.html
+++ b/use/bufio..ReadWriter.html
@@ -22,7 +22,7 @@
responsecontroller.go#L66: func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error) {
server.go#L206: Hijack() (net.Conn, *bufio.ReadWriter, error)
server.go#L317: func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
- server.go#L2199: func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
+ server.go#L2201: func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {