1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // HTTP server. See RFC 7230 through 7235.
33 "golang.org/x/net/http/httpguts"
38 // Errors used by the HTTP server.
40 // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
41 // when the HTTP method or response code does not permit a
43 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
45 // ErrHijacked is returned by ResponseWriter.Write calls when
46 // the underlying connection has been hijacked using the
47 // Hijacker interface. A zero-byte write on a hijacked
48 // connection will return ErrHijacked without any other side
50 ErrHijacked = errors.New("http: connection has been hijacked")
52 // ErrContentLength is returned by ResponseWriter.Write calls
53 // when a Handler set a Content-Length response header with a
54 // declared size and then attempted to write more bytes than
56 ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
58 // Deprecated: ErrWriteAfterFlush is no longer returned by
59 // anything in the net/http package. Callers should not
60 // compare errors against this variable.
61 ErrWriteAfterFlush = errors.New("unused")
64 // A Handler responds to an HTTP request.
66 // ServeHTTP should write reply headers and data to the [ResponseWriter]
67 // and then return. Returning signals that the request is finished; it
68 // is not valid to use the [ResponseWriter] or read from the
69 // [Request.Body] after or concurrently with the completion of the
72 // Depending on the HTTP client software, HTTP protocol version, and
73 // any intermediaries between the client and the Go server, it may not
74 // be possible to read from the [Request.Body] after writing to the
75 // [ResponseWriter]. Cautious handlers should read the [Request.Body]
76 // first, and then reply.
78 // Except for reading the body, handlers should not modify the
81 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
82 // that the effect of the panic was isolated to the active request.
83 // It recovers the panic, logs a stack trace to the server error log,
84 // and either closes the network connection or sends an HTTP/2
85 // RST_STREAM, depending on the HTTP protocol. To abort a handler so
86 // the client sees an interrupted response but the server doesn't log
87 // an error, panic with the value [ErrAbortHandler].
88 type Handler interface {
89 ServeHTTP(ResponseWriter, *Request)
92 // A ResponseWriter interface is used by an HTTP handler to
93 // construct an HTTP response.
95 // A ResponseWriter may not be used after [Handler.ServeHTTP] has returned.
96 type ResponseWriter interface {
97 // Header returns the header map that will be sent by
98 // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
99 // [Handler] implementations can set HTTP trailers.
101 // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
102 // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
103 // 1xx class or the modified headers are trailers.
105 // There are two ways to set Trailers. The preferred way is to
106 // predeclare in the headers which trailers you will later
107 // send by setting the "Trailer" header to the names of the
108 // trailer keys which will come later. In this case, those
109 // keys of the Header map are treated as if they were
110 // trailers. See the example. The second way, for trailer
111 // keys not known to the [Handler] until after the first [ResponseWriter.Write],
112 // is to prefix the [Header] map keys with the [TrailerPrefix]
115 // To suppress automatic response headers (such as "Date"), set
116 // their value to nil.
119 // Write writes the data to the connection as part of an HTTP reply.
121 // If [ResponseWriter.WriteHeader] has not yet been called, Write calls
122 // WriteHeader(http.StatusOK) before writing the data. If the Header
123 // does not contain a Content-Type line, Write adds a Content-Type set
124 // to the result of passing the initial 512 bytes of written data to
125 // [DetectContentType]. Additionally, if the total size of all written
126 // data is under a few KB and there are no Flush calls, the
127 // Content-Length header is added automatically.
129 // Depending on the HTTP protocol version and the client, calling
130 // Write or WriteHeader may prevent future reads on the
131 // Request.Body. For HTTP/1.x requests, handlers should read any
132 // needed request body data before writing the response. Once the
133 // headers have been flushed (due to either an explicit Flusher.Flush
134 // call or writing enough data to trigger a flush), the request body
135 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
136 // handlers to continue to read the request body while concurrently
137 // writing the response. However, such behavior may not be supported
138 // by all HTTP/2 clients. Handlers should read before writing if
139 // possible to maximize compatibility.
140 Write([]byte) (int, error)
142 // WriteHeader sends an HTTP response header with the provided
145 // If WriteHeader is not called explicitly, the first call to Write
146 // will trigger an implicit WriteHeader(http.StatusOK).
147 // Thus explicit calls to WriteHeader are mainly used to
148 // send error codes or 1xx informational responses.
150 // The provided code must be a valid HTTP 1xx-5xx status code.
151 // Any number of 1xx headers may be written, followed by at most
152 // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
153 // headers may be buffered. Use the Flusher interface to send
154 // buffered data. The header map is cleared when 2xx-5xx headers are
155 // sent, but not with 1xx headers.
157 // The server will automatically send a 100 (Continue) header
158 // on the first read from the request body if the request has
159 // an "Expect: 100-continue" header.
160 WriteHeader(statusCode int)
163 // The Flusher interface is implemented by ResponseWriters that allow
164 // an HTTP handler to flush buffered data to the client.
166 // The default HTTP/1.x and HTTP/2 ResponseWriter implementations
167 // support Flusher, but ResponseWriter wrappers may not. Handlers
168 // should always test for this ability at runtime.
170 // Note that even for ResponseWriters that support Flush,
171 // if the client is connected through an HTTP proxy,
172 // the buffered data may not reach the client until the response
174 type Flusher interface {
175 // Flush sends any buffered data to the client.
179 // The Hijacker interface is implemented by ResponseWriters that allow
180 // an HTTP handler to take over the connection.
182 // The default ResponseWriter for HTTP/1.x connections supports
183 // Hijacker, but HTTP/2 connections intentionally do not.
184 // ResponseWriter wrappers may also not support Hijacker. Handlers
185 // should always test for this ability at runtime.
186 type Hijacker interface {
187 // Hijack lets the caller take over the connection.
188 // After a call to Hijack the HTTP server library
189 // will not do anything else with the connection.
191 // It becomes the caller's responsibility to manage
192 // and close the connection.
194 // The returned net.Conn may have read or write deadlines
195 // already set, depending on the configuration of the
196 // Server. It is the caller's responsibility to set
197 // or clear those deadlines as needed.
199 // The returned bufio.Reader may contain unprocessed buffered
200 // data from the client.
202 // After a call to Hijack, the original Request.Body must not
203 // be used. The original Request's Context remains valid and
204 // is not canceled until the Request's ServeHTTP method
206 Hijack() (net.Conn, *bufio.ReadWriter, error)
209 // The CloseNotifier interface is implemented by ResponseWriters which
210 // allow detecting when the underlying connection has gone away.
212 // This mechanism can be used to cancel long operations on the server
213 // if the client has disconnected before the response is ready.
215 // Deprecated: the CloseNotifier interface predates Go's context package.
216 // New code should use Request.Context instead.
217 type CloseNotifier interface {
218 // CloseNotify returns a channel that receives at most a
219 // single value (true) when the client connection has gone
222 // CloseNotify may wait to notify until Request.Body has been
225 // After the Handler has returned, there is no guarantee
226 // that the channel receives a value.
228 // If the protocol is HTTP/1.1 and CloseNotify is called while
229 // processing an idempotent request (such a GET) while
230 // HTTP/1.1 pipelining is in use, the arrival of a subsequent
231 // pipelined request may cause a value to be sent on the
232 // returned channel. In practice HTTP/1.1 pipelining is not
233 // enabled in browsers and not seen often in the wild. If this
234 // is a problem, use HTTP/2 or only use CloseNotify on methods
236 CloseNotify() <-chan bool
240 // ServerContextKey is a context key. It can be used in HTTP
241 // handlers with Context.Value to access the server that
242 // started the handler. The associated value will be of
244 ServerContextKey = &contextKey{"http-server"}
246 // LocalAddrContextKey is a context key. It can be used in
247 // HTTP handlers with Context.Value to access the local
248 // address the connection arrived on.
249 // The associated value will be of type net.Addr.
250 LocalAddrContextKey = &contextKey{"local-addr"}
253 // A conn represents the server side of an HTTP connection.
255 // server is the server on which the connection arrived.
256 // Immutable; never nil.
259 // cancelCtx cancels the connection-level context.
260 cancelCtx context.CancelFunc
262 // rwc is the underlying network connection.
263 // This is never wrapped by other types and is the value given out
264 // to CloseNotifier callers. It is usually of type *net.TCPConn or
268 // remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
269 // inside the Listener's Accept goroutine, as some implementations block.
270 // It is populated immediately inside the (*conn).serve goroutine.
271 // This is the value of a Handler's (*Request).RemoteAddr.
274 // tlsState is the TLS connection state when using TLS.
275 // nil means not TLS.
276 tlsState *tls.ConnectionState
278 // werr is set to the first write error to rwc.
279 // It is set via checkConnErrorWriter{w}, where bufw writes.
282 // r is bufr's read source. It's a wrapper around rwc that provides
283 // io.LimitedReader-style limiting (while reading request headers)
284 // and functionality to support CloseNotifier. See *connReader docs.
287 // bufr reads from r.
290 // bufw writes to checkConnErrorWriter{c}, which populates werr on error.
293 // lastMethod is the method of the most recent request
294 // on this connection, if any.
297 curReq atomic.Pointer[response] // (which has a Request in it)
299 curState atomic.Uint64 // packed (unixtime<<8|uint8(ConnState))
301 // mu guards hijackedv
304 // hijackedv is whether this connection has been hijacked
305 // by a Handler with the Hijacker interface.
306 // It is guarded by mu.
310 func (c *conn) hijacked() bool {
316 // c.mu must be held.
317 func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
319 return nil, nil, ErrHijacked
321 c.r.abortPendingRead()
325 rwc.SetDeadline(time.Time{})
327 buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
329 if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
330 return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
333 c.setState(rwc, StateHijacked, runHooks)
337 // This should be >= 512 bytes for DetectContentType,
338 // but otherwise it's somewhat arbitrary.
339 const bufferBeforeChunkingSize = 2048
341 // chunkWriter writes to a response's conn buffer, and is the writer
342 // wrapped by the response.w buffered writer.
344 // chunkWriter also is responsible for finalizing the Header, including
345 // conditionally setting the Content-Type and setting a Content-Length
346 // in cases where the handler's final output is smaller than the buffer
347 // size. It also conditionally adds chunk headers, when in chunking mode.
349 // See the comment above (*response).Write for the entire write flow.
350 type chunkWriter struct {
353 // header is either nil or a deep clone of res.handlerHeader
354 // at the time of res.writeHeader, if res.writeHeader is
355 // called and extra buffering is being done to calculate
356 // Content-Type and/or Content-Length.
359 // wroteHeader tells whether the header's been written to "the
360 // wire" (or rather: w.conn.buf). this is unlike
361 // (*response).wroteHeader, which tells only whether it was
362 // logically written.
365 // set by the writeHeader method:
366 chunking bool // using chunked transfer encoding for reply body
370 crlf = []byte("\r\n")
371 colonSpace = []byte(": ")
374 func (cw *chunkWriter) Write(p []byte) (n int, err error) {
378 if cw.res.req.Method == "HEAD" {
383 _, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
385 cw.res.conn.rwc.Close()
389 n, err = cw.res.conn.bufw.Write(p)
390 if cw.chunking && err == nil {
391 _, err = cw.res.conn.bufw.Write(crlf)
394 cw.res.conn.rwc.Close()
399 func (cw *chunkWriter) flush() error {
403 return cw.res.conn.bufw.Flush()
406 func (cw *chunkWriter) close() {
411 bw := cw.res.conn.bufw // conn's bufio writer
412 // zero chunk to mark EOF
413 bw.WriteString("0\r\n")
414 if trailers := cw.res.finalTrailers(); trailers != nil {
415 trailers.Write(bw) // the writer handles noting errors
417 // final blank line after the trailers (whether
419 bw.WriteString("\r\n")
423 // A response represents the server side of an HTTP response.
424 type response struct {
426 req *Request // request for this response
427 reqBody io.ReadCloser
428 cancelCtx context.CancelFunc // when ServeHTTP exits
429 wroteHeader bool // a non-1xx header has been (logically) written
430 wroteContinue bool // 100 Continue response was written
431 wants10KeepAlive bool // HTTP/1.0 w/ Connection "keep-alive"
432 wantsClose bool // HTTP request has Connection "close"
434 // canWriteContinue is an atomic boolean that says whether or
435 // not a 100 Continue header can be written to the
437 // writeContinueMu must be held while writing the header.
438 // These two fields together synchronize the body reader (the
439 // expectContinueReader, which wants to write 100 Continue)
440 // against the main writer.
441 canWriteContinue atomic.Bool
442 writeContinueMu sync.Mutex
444 w *bufio.Writer // buffers output in chunks to chunkWriter
447 // handlerHeader is the Header that Handlers get access to,
448 // which may be retained and mutated even after WriteHeader.
449 // handlerHeader is copied into cw.header at WriteHeader
450 // time, and privately mutated thereafter.
452 calledHeader bool // handler accessed handlerHeader via Header
454 written int64 // number of bytes written in body
455 contentLength int64 // explicitly-declared Content-Length; or -1
456 status int // status code passed to WriteHeader
458 // close connection after this reply. set on request and
459 // updated after response from handler if there's a
460 // "Connection: keep-alive" response header and a
464 // When fullDuplex is false (the default), we consume any remaining
465 // request body before starting to write a response.
468 // requestBodyLimitHit is set by requestTooLarge when
469 // maxBytesReader hits its max size. It is checked in
470 // WriteHeader, to make sure we don't consume the
471 // remaining request body to try to advance to the next HTTP
472 // request. Instead, when this is set, we stop reading
473 // subsequent requests on this connection and stop reading
475 requestBodyLimitHit bool
477 // trailers are the headers to be sent after the handler
478 // finishes writing the body. This field is initialized from
479 // the Trailer response header when the response header is
483 handlerDone atomic.Bool // set true when the handler exits
485 // Buffers for Date, Content-Length, and status code
486 dateBuf [len(TimeFormat)]byte
490 // closeNotifyCh is the channel returned by CloseNotify.
491 // TODO(bradfitz): this is currently (for Go 1.8) always
492 // non-nil. Make this lazily-created again as it used to be?
493 closeNotifyCh chan bool
494 didCloseNotify atomic.Bool // atomic (only false->true winner should send)
497 func (c *response) SetReadDeadline(deadline time.Time) error {
498 return c.conn.rwc.SetReadDeadline(deadline)
501 func (c *response) SetWriteDeadline(deadline time.Time) error {
502 return c.conn.rwc.SetWriteDeadline(deadline)
505 func (c *response) EnableFullDuplex() error {
510 // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
511 // that, if present, signals that the map entry is actually for
512 // the response trailers, and not the response headers. The prefix
513 // is stripped after the ServeHTTP call finishes and the values are
514 // sent in the trailers.
516 // This mechanism is intended only for trailers that are not known
517 // prior to the headers being written. If the set of trailers is fixed
518 // or known before the header is written, the normal Go trailers mechanism
521 // https://pkg.go.dev/net/http#ResponseWriter
522 // https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
523 const TrailerPrefix = "Trailer:"
525 // finalTrailers is called after the Handler exits and returns a non-nil
526 // value if the Handler set any trailers.
527 func (w *response) finalTrailers() Header {
529 for k, vv := range w.handlerHeader {
530 if kk, found := strings.CutPrefix(k, TrailerPrefix); found {
537 for _, k := range w.trailers {
541 for _, v := range w.handlerHeader[k] {
548 // declareTrailer is called for each Trailer header when the
549 // response header is written. It notes that a header will need to be
550 // written in the trailers at the end of the response.
551 func (w *response) declareTrailer(k string) {
552 k = CanonicalHeaderKey(k)
553 if !httpguts.ValidTrailerHeader(k) {
554 // Forbidden by RFC 7230, section 4.1.2
557 w.trailers = append(w.trailers, k)
560 // requestTooLarge is called by maxBytesReader when too much input has
561 // been read from the client.
562 func (w *response) requestTooLarge() {
563 w.closeAfterReply = true
564 w.requestBodyLimitHit = true
566 w.Header().Set("Connection", "close")
570 // writerOnly hides an io.Writer value's optional ReadFrom method
572 type writerOnly struct {
576 // ReadFrom is here to optimize copying from an *os.File regular file
577 // to a *net.TCPConn with sendfile, or from a supported src type such
578 // as a *net.TCPConn on Linux with splice.
579 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
580 bufp := copyBufPool.Get().(*[]byte)
582 defer copyBufPool.Put(bufp)
584 // Our underlying w.conn.rwc is usually a *TCPConn (with its
585 // own ReadFrom method). If not, just fall back to the normal
587 rf, ok := w.conn.rwc.(io.ReaderFrom)
589 return io.CopyBuffer(writerOnly{w}, src, buf)
592 // Copy the first sniffLen bytes before switching to ReadFrom.
593 // This ensures we don't start writing the response before the
594 // source is available (see golang.org/issue/5660) and provides
595 // enough bytes to perform Content-Type sniffing when required.
596 if !w.cw.wroteHeader {
597 n0, err := io.CopyBuffer(writerOnly{w}, io.LimitReader(src, sniffLen), buf)
599 if err != nil || n0 < sniffLen {
604 w.w.Flush() // get rid of any previous writes
605 w.cw.flush() // make sure Header is written; flush data to rwc
607 // Now that cw has been flushed, its chunking field is guaranteed initialized.
608 if !w.cw.chunking && w.bodyAllowed() {
609 n0, err := rf.ReadFrom(src)
615 n0, err := io.CopyBuffer(writerOnly{w}, src, buf)
620 // debugServerConnections controls whether all server connections are wrapped
621 // with a verbose logging wrapper.
622 const debugServerConnections = false
624 // Create new connection from rwc.
625 func (srv *Server) newConn(rwc net.Conn) *conn {
630 if debugServerConnections {
631 c.rwc = newLoggingConn("server", c.rwc)
636 type readResult struct {
640 b byte // byte read, if n == 1
643 // connReader is the io.Reader wrapper used by *conn. It combines a
644 // selectively-activated io.LimitedReader (to bound request header
645 // read sizes) with support for selectively keeping an io.Reader.Read
646 // call blocked in a background goroutine to wait for activity and
647 // trigger a CloseNotifier channel.
648 type connReader struct {
651 mu sync.Mutex // guards following
656 aborted bool // set true before conn.rwc deadline is set to past
657 remain int64 // bytes remaining
660 func (cr *connReader) lock() {
663 cr.cond = sync.NewCond(&cr.mu)
667 func (cr *connReader) unlock() { cr.mu.Unlock() }
669 func (cr *connReader) startBackgroundRead() {
673 panic("invalid concurrent Body.Read call")
679 cr.conn.rwc.SetReadDeadline(time.Time{})
680 go cr.backgroundRead()
683 func (cr *connReader) backgroundRead() {
684 n, err := cr.conn.rwc.Read(cr.byteBuf[:])
688 // We were past the end of the previous request's body already
689 // (since we wouldn't be in a background read otherwise), so
690 // this is a pipelined HTTP request. Prior to Go 1.11 we used to
691 // send on the CloseNotify channel and cancel the context here,
692 // but the behavior was documented as only "may", and we only
693 // did that because that's how CloseNotify accidentally behaved
694 // in very early Go releases prior to context support. Once we
695 // added context support, people used a Handler's
696 // Request.Context() and passed it along. Having that context
697 // cancel on pipelined HTTP requests caused problems.
698 // Fortunately, almost nothing uses HTTP/1.x pipelining.
699 // Unfortunately, apt-get does, or sometimes does.
700 // New Go 1.11 behavior: don't fire CloseNotify or cancel
701 // contexts on pipelined requests. Shouldn't affect people, but
702 // fixes cases like Issue 23921. This does mean that a client
703 // closing their TCP connection after sending a pipelined
704 // request won't cancel the context, but we'll catch that on any
705 // write failure (in checkConnErrorWriter.Write).
706 // If the server never writes, yes, there are still contrived
707 // server & client behaviors where this fails to ever cancel the
708 // context, but that's kinda why HTTP/1.x pipelining died
711 if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
712 // Ignore this error. It's the expected error from
713 // another goroutine calling abortPendingRead.
714 } else if err != nil {
715 cr.handleReadError(err)
723 func (cr *connReader) abortPendingRead() {
730 cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
734 cr.conn.rwc.SetReadDeadline(time.Time{})
737 func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
738 func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 }
739 func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 }
741 // handleReadError is called whenever a Read from the client returns a
744 // The provided non-nil err is almost always io.EOF or a "use of
745 // closed network connection". In any case, the error is not
746 // particularly interesting, except perhaps for debugging during
747 // development. Any error means the connection is dead and we should
750 // It may be called from multiple goroutines.
751 func (cr *connReader) handleReadError(_ error) {
756 // may be called from multiple goroutines.
757 func (cr *connReader) closeNotify() {
758 res := cr.conn.curReq.Load()
759 if res != nil && !res.didCloseNotify.Swap(true) {
760 res.closeNotifyCh <- true
764 func (cr *connReader) Read(p []byte) (n int, err error) {
768 if cr.conn.hijacked() {
769 panic("invalid Body.Read call. After hijacked, the original Request must not be used")
771 panic("invalid concurrent Body.Read call")
773 if cr.hitReadLimit() {
781 if int64(len(p)) > cr.remain {
792 n, err = cr.conn.rwc.Read(p)
797 cr.handleReadError(err)
799 cr.remain -= int64(n)
807 bufioReaderPool sync.Pool
808 bufioWriter2kPool sync.Pool
809 bufioWriter4kPool sync.Pool
812 var copyBufPool = sync.Pool{
814 b := make([]byte, 32*1024)
819 func bufioWriterPool(size int) *sync.Pool {
822 return &bufioWriter2kPool
824 return &bufioWriter4kPool
829 func newBufioReader(r io.Reader) *bufio.Reader {
830 if v := bufioReaderPool.Get(); v != nil {
831 br := v.(*bufio.Reader)
835 // Note: if this reader size is ever changed, update
836 // TestHandlerBodyClose's assumptions.
837 return bufio.NewReader(r)
840 func putBufioReader(br *bufio.Reader) {
842 bufioReaderPool.Put(br)
845 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
846 pool := bufioWriterPool(size)
848 if v := pool.Get(); v != nil {
849 bw := v.(*bufio.Writer)
854 return bufio.NewWriterSize(w, size)
857 func putBufioWriter(bw *bufio.Writer) {
859 if pool := bufioWriterPool(bw.Available()); pool != nil {
864 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
865 // in an HTTP request.
866 // This can be overridden by setting Server.MaxHeaderBytes.
867 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
869 func (srv *Server) maxHeaderBytes() int {
870 if srv.MaxHeaderBytes > 0 {
871 return srv.MaxHeaderBytes
873 return DefaultMaxHeaderBytes
876 func (srv *Server) initialReadLimitSize() int64 {
877 return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
880 // tlsHandshakeTimeout returns the time limit permitted for the TLS
881 // handshake, or zero for unlimited.
883 // It returns the minimum of any positive ReadHeaderTimeout,
884 // ReadTimeout, or WriteTimeout.
885 func (srv *Server) tlsHandshakeTimeout() time.Duration {
886 var ret time.Duration
887 for _, v := range [...]time.Duration{
888 srv.ReadHeaderTimeout,
895 if ret == 0 || v < ret {
902 // wrapper around io.ReadCloser which on first read, sends an
903 // HTTP/1.1 100 Continue header
904 type expectContinueReader struct {
906 readCloser io.ReadCloser
911 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
912 if ecr.closed.Load() {
913 return 0, ErrBodyReadAfterClose
916 if !w.wroteContinue && w.canWriteContinue.Load() && !w.conn.hijacked() {
917 w.wroteContinue = true
918 w.writeContinueMu.Lock()
919 if w.canWriteContinue.Load() {
920 w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
922 w.canWriteContinue.Store(false)
924 w.writeContinueMu.Unlock()
926 n, err = ecr.readCloser.Read(p)
928 ecr.sawEOF.Store(true)
933 func (ecr *expectContinueReader) Close() error {
934 ecr.closed.Store(true)
935 return ecr.readCloser.Close()
938 // TimeFormat is the time format to use when generating times in HTTP
939 // headers. It is like time.RFC1123 but hard-codes GMT as the time
940 // zone. The time being formatted must be in UTC for Format to
941 // generate the correct format.
943 // For parsing this time format, see ParseTime.
944 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
946 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
947 func appendTime(b []byte, t time.Time) []byte {
948 const days = "SunMonTueWedThuFriSat"
949 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
952 yy, mm, dd := t.Date()
953 hh, mn, ss := t.Clock()
954 day := days[3*t.Weekday():]
955 mon := months[3*(mm-1):]
958 day[0], day[1], day[2], ',', ' ',
959 byte('0'+dd/10), byte('0'+dd%10), ' ',
960 mon[0], mon[1], mon[2], ' ',
961 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
962 byte('0'+hh/10), byte('0'+hh%10), ':',
963 byte('0'+mn/10), byte('0'+mn%10), ':',
964 byte('0'+ss/10), byte('0'+ss%10), ' ',
968 var errTooLarge = errors.New("http: request too large")
970 // Read next request from connection.
971 func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
973 return nil, ErrHijacked
977 wholeReqDeadline time.Time // or zero if none
978 hdrDeadline time.Time // or zero if none
981 if d := c.server.readHeaderTimeout(); d > 0 {
982 hdrDeadline = t0.Add(d)
984 if d := c.server.ReadTimeout; d > 0 {
985 wholeReqDeadline = t0.Add(d)
987 c.rwc.SetReadDeadline(hdrDeadline)
988 if d := c.server.WriteTimeout; d > 0 {
990 c.rwc.SetWriteDeadline(time.Now().Add(d))
994 c.r.setReadLimit(c.server.initialReadLimitSize())
995 if c.lastMethod == "POST" {
996 // RFC 7230 section 3 tolerance for old buggy clients.
997 peek, _ := c.bufr.Peek(4) // ReadRequest will get err below
998 c.bufr.Discard(numLeadingCRorLF(peek))
1000 req, err := readRequest(c.bufr)
1002 if c.r.hitReadLimit() {
1003 return nil, errTooLarge
1008 if !http1ServerSupportsRequest(req) {
1009 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"}
1012 c.lastMethod = req.Method
1013 c.r.setInfiniteReadLimit()
1015 hosts, haveHost := req.Header["Host"]
1016 isH2Upgrade := req.isH2Upgrade()
1017 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
1018 return nil, badRequestError("missing required Host header")
1020 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
1021 return nil, badRequestError("malformed Host header")
1023 for k, vv := range req.Header {
1024 if !httpguts.ValidHeaderFieldName(k) {
1025 return nil, badRequestError("invalid header name")
1027 for _, v := range vv {
1028 if !httpguts.ValidHeaderFieldValue(v) {
1029 return nil, badRequestError("invalid header value")
1033 delete(req.Header, "Host")
1035 ctx, cancelCtx := context.WithCancel(ctx)
1037 req.RemoteAddr = c.remoteAddr
1038 req.TLS = c.tlsState
1039 if body, ok := req.Body.(*body); ok {
1040 body.doEarlyClose = true
1043 // Adjust the read deadline if necessary.
1044 if !hdrDeadline.Equal(wholeReqDeadline) {
1045 c.rwc.SetReadDeadline(wholeReqDeadline)
1050 cancelCtx: cancelCtx,
1053 handlerHeader: make(Header),
1055 closeNotifyCh: make(chan bool, 1),
1057 // We populate these ahead of time so we're not
1058 // reading from req.Header after their Handler starts
1059 // and maybe mutates it (Issue 14940)
1060 wants10KeepAlive: req.wantsHttp10KeepAlive(),
1061 wantsClose: req.wantsClose(),
1064 w.closeAfterReply = true
1067 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
1071 // http1ServerSupportsRequest reports whether Go's HTTP/1.x server
1072 // supports the given request.
1073 func http1ServerSupportsRequest(req *Request) bool {
1074 if req.ProtoMajor == 1 {
1077 // Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
1078 // wire up their own HTTP/2 upgrades.
1079 if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
1080 req.Method == "PRI" && req.RequestURI == "*" {
1083 // Reject HTTP/0.x, and all other HTTP/2+ requests (which
1084 // aren't encoded in ASCII anyway).
1088 func (w *response) Header() Header {
1089 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
1090 // Accessing the header between logically writing it
1091 // and physically writing it means we need to allocate
1092 // a clone to snapshot the logically written state.
1093 w.cw.header = w.handlerHeader.Clone()
1095 w.calledHeader = true
1096 return w.handlerHeader
1099 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
1100 // consumed by a handler that the server will read from the client
1101 // in order to keep a connection alive. If there are more bytes than
1102 // this then the server to be paranoid instead sends a "Connection:
1105 // This number is approximately what a typical machine's TCP buffer
1106 // size is anyway. (if we have the bytes on the machine, we might as
1108 const maxPostHandlerReadBytes = 256 << 10
1110 func checkWriteHeaderCode(code int) {
1111 // Issue 22880: require valid WriteHeader status codes.
1112 // For now we only enforce that it's three digits.
1113 // In the future we might block things over 599 (600 and above aren't defined
1114 // at https://httpwg.org/specs/rfc7231.html#status.codes).
1115 // But for now any three digits.
1117 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
1118 // no equivalent bogus thing we can realistically send in HTTP/2,
1119 // so we'll consistently panic instead and help people find their bugs
1120 // early. (We can't return an error from WriteHeader even if we wanted to.)
1121 if code < 100 || code > 999 {
1122 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
1126 // relevantCaller searches the call stack for the first function outside of net/http.
1127 // The purpose of this function is to provide more helpful error messages.
1128 func relevantCaller() runtime.Frame {
1129 pc := make([]uintptr, 16)
1130 n := runtime.Callers(1, pc)
1131 frames := runtime.CallersFrames(pc[:n])
1132 var frame runtime.Frame
1134 frame, more := frames.Next()
1135 if !strings.HasPrefix(frame.Function, "net/http.") {
1145 func (w *response) WriteHeader(code int) {
1146 if w.conn.hijacked() {
1147 caller := relevantCaller()
1148 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1152 caller := relevantCaller()
1153 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1156 checkWriteHeaderCode(code)
1158 // Handle informational headers.
1160 // We shouldn't send any further headers after 101 Switching Protocols,
1161 // so it takes the non-informational path.
1162 if code >= 100 && code <= 199 && code != StatusSwitchingProtocols {
1163 // Prevent a potential race with an automatically-sent 100 Continue triggered by Request.Body.Read()
1164 if code == 100 && w.canWriteContinue.Load() {
1165 w.writeContinueMu.Lock()
1166 w.canWriteContinue.Store(false)
1167 w.writeContinueMu.Unlock()
1170 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1172 // Per RFC 8297 we must not clear the current header map
1173 w.handlerHeader.WriteSubset(w.conn.bufw, excludedHeadersNoBody)
1174 w.conn.bufw.Write(crlf)
1180 w.wroteHeader = true
1183 if w.calledHeader && w.cw.header == nil {
1184 w.cw.header = w.handlerHeader.Clone()
1187 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
1188 v, err := strconv.ParseInt(cl, 10, 64)
1189 if err == nil && v >= 0 {
1192 w.conn.server.logf("http: invalid Content-Length of %q", cl)
1193 w.handlerHeader.Del("Content-Length")
1198 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
1199 // This type is used to avoid extra allocations from cloning and/or populating
1200 // the response Header map and all its 1-element slices.
1201 type extraHeader struct {
1204 transferEncoding string
1205 date []byte // written if not nil
1206 contentLength []byte // written if not nil
1209 // Sorted the same as extraHeader.Write's loop.
1210 var extraHeaderKeys = [][]byte{
1211 []byte("Content-Type"),
1212 []byte("Connection"),
1213 []byte("Transfer-Encoding"),
1217 headerContentLength = []byte("Content-Length: ")
1218 headerDate = []byte("Date: ")
1221 // Write writes the headers described in h to w.
1223 // This method has a value receiver, despite the somewhat large size
1224 // of h, because it prevents an allocation. The escape analysis isn't
1225 // smart enough to realize this function doesn't mutate h.
1226 func (h extraHeader) Write(w *bufio.Writer) {
1232 if h.contentLength != nil {
1233 w.Write(headerContentLength)
1234 w.Write(h.contentLength)
1237 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
1239 w.Write(extraHeaderKeys[i])
1247 // writeHeader finalizes the header sent to the client and writes it
1248 // to cw.res.conn.bufw.
1250 // p is not written by writeHeader, but is the first chunk of the body
1251 // that will be written. It is sniffed for a Content-Type if none is
1252 // set explicitly. It's also used to set the Content-Length, if the
1253 // total body size was small and the handler has already finished
1255 func (cw *chunkWriter) writeHeader(p []byte) {
1259 cw.wroteHeader = true
1262 keepAlivesEnabled := w.conn.server.doKeepAlives()
1263 isHEAD := w.req.Method == "HEAD"
1265 // header is written out to w.conn.buf below. Depending on the
1266 // state of the handler, we either own the map or not. If we
1267 // don't own it, the exclude map is created lazily for
1268 // WriteSubset to remove headers. The setHeader struct holds
1269 // headers we need to add.
1271 owned := header != nil
1273 header = w.handlerHeader
1275 var excludeHeader map[string]bool
1276 delHeader := func(key string) {
1281 if _, ok := header[key]; !ok {
1284 if excludeHeader == nil {
1285 excludeHeader = make(map[string]bool)
1287 excludeHeader[key] = true
1289 var setHeader extraHeader
1291 // Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
1293 for k := range cw.header {
1294 if strings.HasPrefix(k, TrailerPrefix) {
1295 if excludeHeader == nil {
1296 excludeHeader = make(map[string]bool)
1298 excludeHeader[k] = true
1302 for _, v := range cw.header["Trailer"] {
1304 foreachHeaderElement(v, cw.res.declareTrailer)
1307 te := header.get("Transfer-Encoding")
1310 // If the handler is done but never sent a Content-Length
1311 // response header and this is our first (and last) write, set
1312 // it, even to zero. This helps HTTP/1.0 clients keep their
1313 // "keep-alive" connections alive.
1314 // Exceptions: 304/204/1xx responses never get Content-Length, and if
1315 // it was a HEAD request, we don't know the difference between
1316 // 0 actual bytes and 0 bytes because the handler noticed it
1317 // was a HEAD request and chose not to write anything. So for
1318 // HEAD, the handler should either write the Content-Length or
1319 // write non-zero bytes. If it's actually 0 bytes and the
1320 // handler never looked at the Request.Method, we just don't
1321 // send a Content-Length header.
1322 // Further, we don't send an automatic Content-Length if they
1323 // set a Transfer-Encoding, because they're generally incompatible.
1324 if w.handlerDone.Load() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && !header.has("Content-Length") && (!isHEAD || len(p) > 0) {
1325 w.contentLength = int64(len(p))
1326 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
1329 // If this was an HTTP/1.0 request with keep-alive and we sent a
1330 // Content-Length back, we can make this a keep-alive response ...
1331 if w.wants10KeepAlive && keepAlivesEnabled {
1332 sentLength := header.get("Content-Length") != ""
1333 if sentLength && header.get("Connection") == "keep-alive" {
1334 w.closeAfterReply = false
1338 // Check for an explicit (and valid) Content-Length header.
1339 hasCL := w.contentLength != -1
1341 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
1342 _, connectionHeaderSet := header["Connection"]
1343 if !connectionHeaderSet {
1344 setHeader.connection = "keep-alive"
1346 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
1347 w.closeAfterReply = true
1350 if header.get("Connection") == "close" || !keepAlivesEnabled {
1351 w.closeAfterReply = true
1354 // If the client wanted a 100-continue but we never sent it to
1355 // them (or, more strictly: we never finished reading their
1356 // request body), don't reuse this connection because it's now
1357 // in an unknown state: we might be sending this response at
1358 // the same time the client is now sending its request body
1359 // after a timeout. (Some HTTP clients send Expect:
1360 // 100-continue but knowing that some servers don't support
1361 // it, the clients set a timer and send the body later anyway)
1362 // If we haven't seen EOF, we can't skip over the unread body
1363 // because we don't know if the next bytes on the wire will be
1364 // the body-following-the-timer or the subsequent request.
1366 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
1367 w.closeAfterReply = true
1370 // We do this by default because there are a number of clients that
1371 // send a full request before starting to read the response, and they
1372 // can deadlock if we start writing the response with unconsumed body
1373 // remaining. See Issue 15527 for some history.
1375 // If full duplex mode has been enabled with ResponseController.EnableFullDuplex,
1376 // then leave the request body alone.
1377 if w.req.ContentLength != 0 && !w.closeAfterReply && !w.fullDuplex {
1378 var discard, tooBig bool
1380 switch bdy := w.req.Body.(type) {
1381 case *expectContinueReader:
1382 if bdy.resp.wroteContinue {
1390 // Body was closed in handler with non-EOF error.
1391 w.closeAfterReply = true
1393 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1404 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1407 // There must be even more data left over.
1409 case ErrBodyReadAfterClose:
1410 // Body was already consumed and closed.
1412 // The remaining body was just consumed, close it.
1413 err = w.reqBody.Close()
1415 w.closeAfterReply = true
1418 // Some other kind of error occurred, like a read timeout, or
1419 // corrupt chunked encoding. In any case, whatever remains
1420 // on the wire must not be parsed as another HTTP request.
1421 w.closeAfterReply = true
1427 delHeader("Connection")
1428 setHeader.connection = "close"
1433 if bodyAllowedForStatus(code) {
1434 // If no content type, apply sniffing algorithm to body.
1435 _, haveType := header["Content-Type"]
1437 // If the Content-Encoding was set and is non-blank,
1438 // we shouldn't sniff the body. See Issue 31753.
1439 ce := header.Get("Content-Encoding")
1440 hasCE := len(ce) > 0
1441 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1442 setHeader.contentType = DetectContentType(p)
1445 for _, k := range suppressedHeaders(code) {
1450 if !header.has("Date") {
1451 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1454 if hasCL && hasTE && te != "identity" {
1455 // TODO: return an error if WriteHeader gets a return parameter
1456 // For now just ignore the Content-Length.
1457 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1458 te, w.contentLength)
1459 delHeader("Content-Length")
1463 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1464 // Response has no body.
1465 delHeader("Transfer-Encoding")
1467 // Content-Length has been provided, so no chunking is to be done.
1468 delHeader("Transfer-Encoding")
1469 } else if w.req.ProtoAtLeast(1, 1) {
1470 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
1471 // content-length has been provided. The connection must be closed after the
1472 // reply is written, and no chunking is to be done. This is the setup
1473 // recommended in the Server-Sent Events candidate recommendation 11,
1475 if hasTE && te == "identity" {
1477 w.closeAfterReply = true
1478 delHeader("Transfer-Encoding")
1480 // HTTP/1.1 or greater: use chunked transfer encoding
1481 // to avoid closing the connection at EOF.
1483 setHeader.transferEncoding = "chunked"
1484 if hasTE && te == "chunked" {
1485 // We will send the chunked Transfer-Encoding header later.
1486 delHeader("Transfer-Encoding")
1490 // HTTP version < 1.1: cannot do chunked transfer
1491 // encoding and we don't know the Content-Length so
1492 // signal EOF by closing connection.
1493 w.closeAfterReply = true
1494 delHeader("Transfer-Encoding") // in case already set
1497 // Cannot use Content-Length with non-identity Transfer-Encoding.
1499 delHeader("Content-Length")
1501 if !w.req.ProtoAtLeast(1, 0) {
1505 // Only override the Connection header if it is not a successful
1506 // protocol switch response and if KeepAlives are not enabled.
1507 // See https://golang.org/issue/36381.
1508 delConnectionHeader := w.closeAfterReply &&
1509 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1510 !isProtocolSwitchResponse(w.status, header)
1511 if delConnectionHeader {
1512 delHeader("Connection")
1513 if w.req.ProtoAtLeast(1, 1) {
1514 setHeader.connection = "close"
1518 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1519 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1520 setHeader.Write(w.conn.bufw)
1521 w.conn.bufw.Write(crlf)
1524 // foreachHeaderElement splits v according to the "#rule" construction
1525 // in RFC 7230 section 7 and calls fn for each non-empty element.
1526 func foreachHeaderElement(v string, fn func(string)) {
1527 v = textproto.TrimString(v)
1531 if !strings.Contains(v, ",") {
1535 for _, f := range strings.Split(v, ",") {
1536 if f = textproto.TrimString(f); f != "" {
1542 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
1543 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
1544 // code is the response status code.
1545 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
1546 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1548 bw.WriteString("HTTP/1.1 ")
1550 bw.WriteString("HTTP/1.0 ")
1552 if text := StatusText(code); text != "" {
1553 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1555 bw.WriteString(text)
1556 bw.WriteString("\r\n")
1558 // don't worry about performance
1559 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1563 // bodyAllowed reports whether a Write is allowed for this response type.
1564 // It's illegal to call this before the header has been flushed.
1565 func (w *response) bodyAllowed() bool {
1569 return bodyAllowedForStatus(w.status)
1572 // The Life Of A Write is like this:
1574 // Handler starts. No header has been sent. The handler can either
1575 // write a header, or just start writing. Writing before sending a header
1576 // sends an implicitly empty 200 OK header.
1578 // If the handler didn't declare a Content-Length up front, we either
1579 // go into chunking mode or, if the handler finishes running before
1580 // the chunking buffer size, we compute a Content-Length and send that
1581 // in the header instead.
1583 // Likewise, if the handler didn't set a Content-Type, we sniff that
1584 // from the initial chunk of output.
1586 // The Writers are wired together like:
1588 // 1. *response (the ResponseWriter) ->
1589 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes ->
1590 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
1591 // and which writes the chunk headers, if needed ->
1592 // 4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to ->
1593 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
1594 // and populates c.werr with it if so, but otherwise writes to ->
1595 // 6. the rwc, the net.Conn.
1597 // TODO(bradfitz): short-circuit some of the buffering when the
1598 // initial header contains both a Content-Type and Content-Length.
1599 // Also short-circuit in (1) when the header's been sent and not in
1600 // chunking mode, writing directly to (4) instead, if (2) has no
1601 // buffered data. More generally, we could short-circuit from (1) to
1602 // (3) even in chunking mode if the write size from (1) is over some
1603 // threshold and nothing is in (2). The answer might be mostly making
1604 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
1605 // with this instead.
1606 func (w *response) Write(data []byte) (n int, err error) {
1607 return w.write(len(data), data, "")
1610 func (w *response) WriteString(data string) (n int, err error) {
1611 return w.write(len(data), nil, data)
1614 // either dataB or dataS is non-zero.
1615 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1616 if w.conn.hijacked() {
1618 caller := relevantCaller()
1619 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1621 return 0, ErrHijacked
1624 if w.canWriteContinue.Load() {
1625 // Body reader wants to write 100 Continue but hasn't yet.
1626 // Tell it not to. The store must be done while holding the lock
1627 // because the lock makes sure that there is not an active write
1628 // this very moment.
1629 w.writeContinueMu.Lock()
1630 w.canWriteContinue.Store(false)
1631 w.writeContinueMu.Unlock()
1635 w.WriteHeader(StatusOK)
1640 if !w.bodyAllowed() {
1641 return 0, ErrBodyNotAllowed
1644 w.written += int64(lenData) // ignoring errors, for errorKludge
1645 if w.contentLength != -1 && w.written > w.contentLength {
1646 return 0, ErrContentLength
1649 return w.w.Write(dataB)
1651 return w.w.WriteString(dataS)
1655 func (w *response) finishRequest() {
1656 w.handlerDone.Store(true)
1659 w.WriteHeader(StatusOK)
1667 w.conn.r.abortPendingRead()
1669 // Close the body (regardless of w.closeAfterReply) so we can
1670 // re-use its bufio.Reader later safely.
1673 if w.req.MultipartForm != nil {
1674 w.req.MultipartForm.RemoveAll()
1678 // shouldReuseConnection reports whether the underlying TCP connection can be reused.
1679 // It must only be called after the handler is done executing.
1680 func (w *response) shouldReuseConnection() bool {
1681 if w.closeAfterReply {
1682 // The request or something set while executing the
1683 // handler indicated we shouldn't reuse this
1688 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1689 // Did not write enough. Avoid getting out of sync.
1693 // There was some error writing to the underlying connection
1694 // during the request, so don't re-use this conn.
1695 if w.conn.werr != nil {
1699 if w.closedRequestBodyEarly() {
1706 func (w *response) closedRequestBodyEarly() bool {
1707 body, ok := w.req.Body.(*body)
1708 return ok && body.didEarlyClose()
1711 func (w *response) Flush() {
1715 func (w *response) FlushError() error {
1717 w.WriteHeader(StatusOK)
1727 func (c *conn) finalFlush() {
1729 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1730 // reader for a future connection.
1731 putBufioReader(c.bufr)
1737 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1738 // writer for a future connection.
1739 putBufioWriter(c.bufw)
1744 // Close the connection.
1745 func (c *conn) close() {
1750 // rstAvoidanceDelay is the amount of time we sleep after closing the
1751 // write side of a TCP connection before closing the entire socket.
1752 // By sleeping, we increase the chances that the client sees our FIN
1753 // and processes its final data before they process the subsequent RST
1754 // from closing a connection with known unread data.
1755 // This RST seems to occur mostly on BSD systems. (And Windows?)
1756 // This timeout is somewhat arbitrary (~latency around the planet),
1757 // and may be modified by tests.
1759 // TODO(bcmills): This should arguably be a server configuration parameter,
1760 // not a hard-coded value.
1761 var rstAvoidanceDelay = 500 * time.Millisecond
1763 type closeWriter interface {
1767 var _ closeWriter = (*net.TCPConn)(nil)
1769 // closeWriteAndWait flushes any outstanding data and sends a FIN packet (if
1770 // client is connected via TCP), signaling that we're done. We then
1771 // pause for a bit, hoping the client processes it before any
1774 // See https://golang.org/issue/3595
1775 func (c *conn) closeWriteAndWait() {
1777 if tcp, ok := c.rwc.(closeWriter); ok {
1781 // When we return from closeWriteAndWait, the caller will fully close the
1782 // connection. If client is still writing to the connection, this will cause
1783 // the write to fail with ECONNRESET or similar. Unfortunately, many TCP
1784 // implementations will also drop unread packets from the client's read buffer
1785 // when a write fails, causing our final response to be truncated away too.
1787 // As a result, https://www.rfc-editor.org/rfc/rfc7230#section-6.6 recommends
1788 // that “[t]he server … continues to read from the connection until it
1789 // receives a corresponding close by the client, or until the server is
1790 // reasonably certain that its own TCP stack has received the client's
1791 // acknowledgement of the packet(s) containing the server's last response.”
1793 // Unfortunately, we have no straightforward way to be “reasonably certain”
1794 // that we have received the client's ACK, and at any rate we don't want to
1795 // allow a misbehaving client to soak up server connections indefinitely by
1796 // withholding an ACK, nor do we want to go through the complexity or overhead
1797 // of using low-level APIs to figure out when a TCP round-trip has completed.
1799 // Instead, we declare that we are “reasonably certain” that we received the
1800 // ACK if maxRSTAvoidanceDelay has elapsed.
1801 time.Sleep(rstAvoidanceDelay)
1804 // validNextProto reports whether the proto is a valid ALPN protocol name.
1805 // Everything is valid except the empty string and built-in protocol types,
1806 // so that those can't be overridden with alternate implementations.
1807 func validNextProto(proto string) bool {
1809 case "", "http/1.1", "http/1.0":
1820 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1824 srv.trackConn(c, true)
1825 case StateHijacked, StateClosed:
1826 srv.trackConn(c, false)
1828 if state > 0xff || state < 0 {
1829 panic("internal error")
1831 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1832 c.curState.Store(packedState)
1836 if hook := srv.ConnState; hook != nil {
1841 func (c *conn) getState() (state ConnState, unixSec int64) {
1842 packedState := c.curState.Load()
1843 return ConnState(packedState & 0xff), int64(packedState >> 8)
1846 // badRequestError is a literal string (used by in the server in HTML,
1847 // unescaped) to tell the user why their request was bad. It should
1848 // be plain text without user info or other embedded errors.
1849 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1851 // statusError is an error used to respond to a request with an HTTP status.
1852 // The text should be plain text without user info or other embedded errors.
1853 type statusError struct {
1858 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1860 // ErrAbortHandler is a sentinel panic value to abort a handler.
1861 // While any panic from ServeHTTP aborts the response to the client,
1862 // panicking with ErrAbortHandler also suppresses logging of a stack
1863 // trace to the server's error log.
1864 var ErrAbortHandler = errors.New("net/http: abort Handler")
1866 // isCommonNetReadError reports whether err is a common error
1867 // encountered during reading a request off the network when the
1868 // client has gone away or had its read fail somehow. This is used to
1869 // determine which logs are interesting enough to log about.
1870 func isCommonNetReadError(err error) bool {
1874 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1877 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1883 // Serve a new connection.
1884 func (c *conn) serve(ctx context.Context) {
1885 if ra := c.rwc.RemoteAddr(); ra != nil {
1886 c.remoteAddr = ra.String()
1888 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1889 var inFlightResponse *response
1891 if err := recover(); err != nil && err != ErrAbortHandler {
1892 const size = 64 << 10
1893 buf := make([]byte, size)
1894 buf = buf[:runtime.Stack(buf, false)]
1895 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1897 if inFlightResponse != nil {
1898 inFlightResponse.cancelCtx()
1901 if inFlightResponse != nil {
1902 inFlightResponse.conn.r.abortPendingRead()
1903 inFlightResponse.reqBody.Close()
1906 c.setState(c.rwc, StateClosed, runHooks)
1910 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1911 tlsTO := c.server.tlsHandshakeTimeout()
1913 dl := time.Now().Add(tlsTO)
1914 c.rwc.SetReadDeadline(dl)
1915 c.rwc.SetWriteDeadline(dl)
1917 if err := tlsConn.HandshakeContext(ctx); err != nil {
1918 // If the handshake failed due to the client not speaking
1919 // TLS, assume they're speaking plaintext HTTP and write a
1920 // 400 response on the TLS conn's underlying net.Conn.
1921 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1922 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1926 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1929 // Restore Conn-level deadlines.
1931 c.rwc.SetReadDeadline(time.Time{})
1932 c.rwc.SetWriteDeadline(time.Time{})
1934 c.tlsState = new(tls.ConnectionState)
1935 *c.tlsState = tlsConn.ConnectionState()
1936 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1937 if fn := c.server.TLSNextProto[proto]; fn != nil {
1938 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1939 // Mark freshly created HTTP/2 as active and prevent any server state hooks
1940 // from being run on these connections. This prevents closeIdleConns from
1941 // closing such connections. See issue https://golang.org/issue/39776.
1942 c.setState(c.rwc, StateActive, skipHooks)
1943 fn(c.server, tlsConn, h)
1949 // HTTP/1.x from here on.
1951 ctx, cancelCtx := context.WithCancel(ctx)
1952 c.cancelCtx = cancelCtx
1955 c.r = &connReader{conn: c}
1956 c.bufr = newBufioReader(c.r)
1957 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1960 w, err := c.readRequest(ctx)
1961 if c.r.remain != c.server.initialReadLimitSize() {
1962 // If we read any bytes off the wire, we're active.
1963 c.setState(c.rwc, StateActive, runHooks)
1966 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1969 case err == errTooLarge:
1970 // Their HTTP client may or may not be
1971 // able to read this if we're
1972 // responding to them and hanging up
1973 // while they're still writing their
1974 // request. Undefined behavior.
1975 const publicErr = "431 Request Header Fields Too Large"
1976 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1977 c.closeWriteAndWait()
1980 case isUnsupportedTEError(err):
1981 // Respond as per RFC 7230 Section 3.3.1 which says,
1982 // A server that receives a request message with a
1983 // transfer coding it does not understand SHOULD
1984 // respond with 501 (Unimplemented).
1985 code := StatusNotImplemented
1987 // We purposefully aren't echoing back the transfer-encoding's value,
1988 // so as to mitigate the risk of cross side scripting by an attacker.
1989 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1992 case isCommonNetReadError(err):
1993 return // don't reply
1996 if v, ok := err.(statusError); ok {
1997 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s: %s%s%d %s: %s", v.code, StatusText(v.code), v.text, errorHeaders, v.code, StatusText(v.code), v.text)
2000 const publicErr = "400 Bad Request"
2001 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
2006 // Expect 100 Continue support
2008 if req.expectsContinue() {
2009 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
2010 // Wrap the Body reader with one that replies on the connection
2011 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
2012 w.canWriteContinue.Store(true)
2014 } else if req.Header.get("Expect") != "" {
2015 w.sendExpectationFailed()
2021 if requestBodyRemains(req.Body) {
2022 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
2024 w.conn.r.startBackgroundRead()
2027 // HTTP cannot have multiple simultaneous active requests.[*]
2028 // Until the server replies to this request, it can't read another,
2029 // so we might as well run the handler in this goroutine.
2030 // [*] Not strictly true: HTTP pipelining. We could let them all process
2031 // in parallel even if their responses need to be serialized.
2032 // But we're not going to implement HTTP pipelining because it
2033 // was never deployed in the wild and the answer is HTTP/2.
2034 inFlightResponse = w
2035 serverHandler{c.server}.ServeHTTP(w, w.req)
2036 inFlightResponse = nil
2042 c.rwc.SetWriteDeadline(time.Time{})
2043 if !w.shouldReuseConnection() {
2044 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
2045 c.closeWriteAndWait()
2049 c.setState(c.rwc, StateIdle, runHooks)
2052 if !w.conn.server.doKeepAlives() {
2053 // We're in shutdown mode. We might've replied
2054 // to the user without "Connection: close" and
2055 // they might think they can send another
2056 // request, but such is life with HTTP/1.1.
2060 if d := c.server.idleTimeout(); d != 0 {
2061 c.rwc.SetReadDeadline(time.Now().Add(d))
2063 c.rwc.SetReadDeadline(time.Time{})
2066 // Wait for the connection to become readable again before trying to
2067 // read the next request. This prevents a ReadHeaderTimeout or
2068 // ReadTimeout from starting until the first bytes of the next request
2069 // have been received.
2070 if _, err := c.bufr.Peek(4); err != nil {
2074 c.rwc.SetReadDeadline(time.Time{})
2078 func (w *response) sendExpectationFailed() {
2079 // TODO(bradfitz): let ServeHTTP handlers handle
2080 // requests with non-standard expectation[s]? Seems
2081 // theoretical at best, and doesn't fit into the
2082 // current ServeHTTP model anyway. We'd need to
2083 // make the ResponseWriter an optional
2084 // "ExpectReplier" interface or something.
2086 // For now we'll just obey RFC 7231 5.1.1 which says
2087 // "A server that receives an Expect field-value other
2088 // than 100-continue MAY respond with a 417 (Expectation
2089 // Failed) status code to indicate that the unexpected
2090 // expectation cannot be met."
2091 w.Header().Set("Connection", "close")
2092 w.WriteHeader(StatusExpectationFailed)
2096 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
2098 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
2099 if w.handlerDone.Load() {
2100 panic("net/http: Hijack called after ServeHTTP finished")
2110 // Release the bufioWriter that writes to the chunk writer, it is not
2111 // used after a connection has been hijacked.
2112 rwc, buf, err = c.hijackLocked()
2117 return rwc, buf, err
2120 func (w *response) CloseNotify() <-chan bool {
2121 if w.handlerDone.Load() {
2122 panic("net/http: CloseNotify called after ServeHTTP finished")
2124 return w.closeNotifyCh
2127 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2128 switch v := rc.(type) {
2129 case *expectContinueReader:
2130 registerOnHitEOF(v.readCloser, fn)
2132 v.registerOnHitEOF(fn)
2134 panic("unexpected type " + fmt.Sprintf("%T", rc))
2138 // requestBodyRemains reports whether future calls to Read
2139 // on rc might yield more data.
2140 func requestBodyRemains(rc io.ReadCloser) bool {
2144 switch v := rc.(type) {
2145 case *expectContinueReader:
2146 return requestBodyRemains(v.readCloser)
2148 return v.bodyRemains()
2150 panic("unexpected type " + fmt.Sprintf("%T", rc))
2154 // The HandlerFunc type is an adapter to allow the use of
2155 // ordinary functions as HTTP handlers. If f is a function
2156 // with the appropriate signature, HandlerFunc(f) is a
2157 // Handler that calls f.
2158 type HandlerFunc func(ResponseWriter, *Request)
2160 // ServeHTTP calls f(w, r).
2161 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2167 // Error replies to the request with the specified error message and HTTP code.
2168 // It does not otherwise end the request; the caller should ensure no further
2169 // writes are done to w.
2170 // The error message should be plain text.
2171 func Error(w ResponseWriter, error string, code int) {
2172 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2173 w.Header().Set("X-Content-Type-Options", "nosniff")
2175 fmt.Fprintln(w, error)
2178 // NotFound replies to the request with an HTTP 404 not found error.
2179 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2181 // NotFoundHandler returns a simple request handler
2182 // that replies to each request with a “404 page not found” reply.
2183 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2185 // StripPrefix returns a handler that serves HTTP requests by removing the
2186 // given prefix from the request URL's Path (and RawPath if set) and invoking
2187 // the handler h. StripPrefix handles a request for a path that doesn't begin
2188 // with prefix by replying with an HTTP 404 not found error. The prefix must
2189 // match exactly: if the prefix in the request contains escaped characters
2190 // the reply is also an HTTP 404 not found error.
2191 func StripPrefix(prefix string, h Handler) Handler {
2195 return HandlerFunc(func(w ResponseWriter, r *Request) {
2196 p := strings.TrimPrefix(r.URL.Path, prefix)
2197 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2198 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2201 r2.URL = new(url.URL)
2212 // Redirect replies to the request with a redirect to url,
2213 // which may be a path relative to the request path.
2215 // The provided code should be in the 3xx range and is usually
2216 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2218 // If the Content-Type header has not been set, Redirect sets it
2219 // to "text/html; charset=utf-8" and writes a small HTML body.
2220 // Setting the Content-Type header to any value, including nil,
2221 // disables that behavior.
2222 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2223 if u, err := urlpkg.Parse(url); err == nil {
2224 // If url was relative, make its path absolute by
2225 // combining with request path.
2226 // The client would probably do this for us,
2227 // but doing it ourselves is more reliable.
2228 // See RFC 7231, section 7.1.2
2229 if u.Scheme == "" && u.Host == "" {
2230 oldpath := r.URL.Path
2231 if oldpath == "" { // should not happen, but avoid a crash if it does
2235 // no leading http://server
2236 if url == "" || url[0] != '/' {
2237 // make relative path absolute
2238 olddir, _ := path.Split(oldpath)
2243 if i := strings.Index(url, "?"); i != -1 {
2244 url, query = url[:i], url[i:]
2247 // clean up but preserve trailing slash
2248 trailing := strings.HasSuffix(url, "/")
2249 url = path.Clean(url)
2250 if trailing && !strings.HasSuffix(url, "/") {
2259 // RFC 7231 notes that a short HTML body is usually included in
2260 // the response because older user agents may not understand 301/307.
2261 // Do it only if the request didn't already have a Content-Type header.
2262 _, hadCT := h["Content-Type"]
2264 h.Set("Location", hexEscapeNonASCII(url))
2265 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2266 h.Set("Content-Type", "text/html; charset=utf-8")
2270 // Shouldn't send the body for POST or HEAD; that leaves GET.
2271 if !hadCT && r.Method == "GET" {
2272 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
2273 fmt.Fprintln(w, body)
2277 var htmlReplacer = strings.NewReplacer(
2281 // """ is shorter than """.
2283 // "'" is shorter than "'" and apos was not in HTML until HTML5.
2287 func htmlEscape(s string) string {
2288 return htmlReplacer.Replace(s)
2291 // Redirect to a fixed URL
2292 type redirectHandler struct {
2297 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2298 Redirect(w, r, rh.url, rh.code)
2301 // RedirectHandler returns a request handler that redirects
2302 // each request it receives to the given url using the given
2305 // The provided code should be in the 3xx range and is usually
2306 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2307 func RedirectHandler(url string, code int) Handler {
2308 return &redirectHandler{url, code}
2311 // TODO(jba): rewrite the following doc for enhanced patterns (proposal
2312 // https://go.dev/issue/61410).
2314 // ServeMux is an HTTP request multiplexer.
2315 // It matches the URL of each incoming request against a list of registered
2316 // patterns and calls the handler for the pattern that
2317 // most closely matches the URL.
2319 // Patterns name fixed, rooted paths, like "/favicon.ico",
2320 // or rooted subtrees, like "/images/" (note the trailing slash).
2321 // Longer patterns take precedence over shorter ones, so that
2322 // if there are handlers registered for both "/images/"
2323 // and "/images/thumbnails/", the latter handler will be
2324 // called for paths beginning with "/images/thumbnails/" and the
2325 // former will receive requests for any other paths in the
2326 // "/images/" subtree.
2328 // Note that since a pattern ending in a slash names a rooted subtree,
2329 // the pattern "/" matches all paths not matched by other registered
2330 // patterns, not just the URL with Path == "/".
2332 // If a subtree has been registered and a request is received naming the
2333 // subtree root without its trailing slash, ServeMux redirects that
2334 // request to the subtree root (adding the trailing slash). This behavior can
2335 // be overridden with a separate registration for the path without
2336 // the trailing slash. For example, registering "/images/" causes ServeMux
2337 // to redirect a request for "/images" to "/images/", unless "/images" has
2338 // been registered separately.
2340 // Patterns may optionally begin with a host name, restricting matches to
2341 // URLs on that host only. Host-specific patterns take precedence over
2342 // general patterns, so that a handler might register for the two patterns
2343 // "/codesearch" and "codesearch.google.com/" without also taking over
2344 // requests for "http://www.google.com/".
2346 // ServeMux also takes care of sanitizing the URL request path and the Host
2347 // header, stripping the port number and redirecting any request containing . or
2348 // .. elements or repeated slashes to an equivalent, cleaner URL.
2349 type ServeMux struct {
2353 patterns []*pattern // TODO(jba): remove if possible
2354 mux121 serveMux121 // used only when GODEBUG=httpmuxgo121=1
2357 // NewServeMux allocates and returns a new ServeMux.
2358 func NewServeMux() *ServeMux {
2362 // DefaultServeMux is the default ServeMux used by Serve.
2363 var DefaultServeMux = &defaultServeMux
2365 var defaultServeMux ServeMux
2367 // cleanPath returns the canonical path for p, eliminating . and .. elements.
2368 func cleanPath(p string) string {
2376 // path.Clean removes trailing slash except for root;
2377 // put the trailing slash back if necessary.
2378 if p[len(p)-1] == '/' && np != "/" {
2379 // Fast path for common case of p being the string we want:
2380 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2389 // stripHostPort returns h without any trailing ":<port>".
2390 func stripHostPort(h string) string {
2391 // If no port on host, return unchanged
2392 if !strings.Contains(h, ":") {
2395 host, _, err := net.SplitHostPort(h)
2397 return h // on error, return unchanged
2402 // Handler returns the handler to use for the given request,
2403 // consulting r.Method, r.Host, and r.URL.Path. It always returns
2404 // a non-nil handler. If the path is not in its canonical form, the
2405 // handler will be an internally-generated handler that redirects
2406 // to the canonical path. If the host contains a port, it is ignored
2407 // when matching handlers.
2409 // The path and host are used unchanged for CONNECT requests.
2411 // Handler also returns the registered pattern that matches the
2412 // request or, in the case of internally-generated redirects,
2413 // the path that will match after following the redirect.
2415 // If there is no registered handler that applies to the request,
2416 // Handler returns a “page not found” handler and an empty pattern.
2417 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2419 return mux.mux121.findHandler(r)
2421 h, p, _, _ := mux.findHandler(r)
2425 // findHandler finds a handler for a request.
2426 // If there is a matching handler, it returns it and the pattern that matched.
2427 // Otherwise it returns a Redirect or NotFound handler with the path that would match
2428 // after the redirect.
2429 func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
2432 escapedPath := r.URL.EscapedPath()
2434 // CONNECT requests are not canonicalized.
2435 if r.Method == "CONNECT" {
2436 // If r.URL.Path is /tree and its handler is not registered,
2437 // the /tree -> /tree/ redirect applies to CONNECT requests
2438 // but the path canonicalization does not.
2439 _, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
2441 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2443 // Redo the match, this time with r.Host instead of r.URL.Host.
2444 // Pass a nil URL to skip the trailing-slash redirect logic.
2445 n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
2447 // All other requests have any port stripped and path cleaned
2448 // before passing to mux.handler.
2449 host = stripHostPort(r.Host)
2450 path = cleanPath(path)
2452 // If the given path is /tree and its handler is not registered,
2453 // redirect for /tree/.
2455 n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
2457 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2459 if path != escapedPath {
2460 // Redirect to cleaned path.
2463 patStr = n.pattern.String()
2465 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2466 return RedirectHandler(u.String(), StatusMovedPermanently), patStr, nil, nil
2470 // We didn't find a match with the request method. To distinguish between
2471 // Not Found and Method Not Allowed, see if there is another pattern that
2472 // matches except for the method.
2473 allowedMethods := mux.matchingMethods(host, path)
2474 if len(allowedMethods) > 0 {
2475 return HandlerFunc(func(w ResponseWriter, r *Request) {
2476 w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
2477 Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
2480 return NotFoundHandler(), "", nil, nil
2482 return n.handler, n.pattern.String(), n.pattern, matches
2485 // matchOrRedirect looks up a node in the tree that matches the host, method and path.
2487 // If the url argument is non-nil, handler also deals with trailing-slash
2488 // redirection: when a path doesn't match exactly, the match is tried again
2489 // after appending "/" to the path. If that second match succeeds, the last
2490 // return value is the URL to redirect to.
2491 func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
2493 defer mux.mu.RUnlock()
2495 n, matches := mux.tree.match(host, method, path)
2496 // If we have an exact match, or we were asked not to try trailing-slash redirection,
2498 if !exactMatch(n, path) && u != nil {
2499 // If there is an exact match with a trailing slash, then redirect.
2501 n2, _ := mux.tree.match(host, method, path)
2502 if exactMatch(n2, path) {
2503 return nil, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
2506 return n, matches, nil
2509 // exactMatch reports whether the node's pattern exactly matches the path.
2510 // As a special case, if the node is nil, exactMatch return false.
2512 // Before wildcards were introduced, it was clear that an exact match meant
2513 // that the pattern and path were the same string. The only other possibility
2514 // was that a trailing-slash pattern, like "/", matched a path longer than
2517 // With wildcards, we define an inexact match as any one where a multi wildcard
2518 // matches a non-empty string. All other matches are exact.
2519 // For example, these are all exact matches:
2527 // The last case has a multi wildcard (implicitly), but the match is exact because
2528 // the wildcard matches the empty string.
2530 // Examples of matches that are not exact:
2535 func exactMatch(n *routingNode, path string) bool {
2539 // We can't directly implement the definition (empty match for multi
2540 // wildcard) because we don't record a match for anonymous multis.
2542 // If there is no multi, the match is exact.
2543 if !n.pattern.lastSegment().multi {
2547 // If the path doesn't end in a trailing slash, then the multi match
2549 if len(path) > 0 && path[len(path)-1] != '/' {
2552 // Only patterns ending in {$} or a multi wildcard can
2553 // match a path with a trailing slash.
2554 // For the match to be exact, the number of pattern
2555 // segments should be the same as the number of slashes in the path.
2556 // E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
2557 return len(n.pattern.segments) == strings.Count(path, "/")
2560 // matchingMethods return a sorted list of all methods that would match with the given host and path.
2561 func (mux *ServeMux) matchingMethods(host, path string) []string {
2562 // Hold the read lock for the entire method so that the two matches are done
2563 // on the same set of registered patterns.
2565 defer mux.mu.RUnlock()
2566 ms := map[string]bool{}
2567 mux.tree.matchingMethods(host, path, ms)
2568 // matchOrRedirect will try appending a trailing slash if there is no match.
2569 mux.tree.matchingMethods(host, path+"/", ms)
2570 methods := mapKeys(ms)
2571 sort.Strings(methods)
2575 // TODO: replace with maps.Keys when it is defined.
2576 func mapKeys[K comparable, V any](m map[K]V) []K {
2584 // ServeHTTP dispatches the request to the handler whose
2585 // pattern most closely matches the request URL.
2586 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2587 if r.RequestURI == "*" {
2588 if r.ProtoAtLeast(1, 1) {
2589 w.Header().Set("Connection", "close")
2591 w.WriteHeader(StatusBadRequest)
2596 h, _ = mux.mux121.findHandler(r)
2598 h, _, r.pat, r.matches = mux.findHandler(r)
2603 // The four functions below all call register so that callerLocation
2604 // always refers to user code.
2606 // Handle registers the handler for the given pattern.
2607 // If a handler already exists for pattern, Handle panics.
2608 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2610 mux.mux121.handle(pattern, handler)
2612 mux.register(pattern, handler)
2615 // HandleFunc registers the handler function for the given pattern.
2616 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2618 mux.mux121.handleFunc(pattern, handler)
2620 mux.register(pattern, HandlerFunc(handler))
2623 // Handle registers the handler for the given pattern in [DefaultServeMux].
2624 // The documentation for [ServeMux] explains how patterns are matched.
2625 func Handle(pattern string, handler Handler) {
2627 DefaultServeMux.mux121.handle(pattern, handler)
2629 DefaultServeMux.register(pattern, handler)
2632 // HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
2633 // The documentation for [ServeMux] explains how patterns are matched.
2634 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2636 DefaultServeMux.mux121.handleFunc(pattern, handler)
2638 DefaultServeMux.register(pattern, HandlerFunc(handler))
2641 func (mux *ServeMux) register(pattern string, handler Handler) {
2642 if err := mux.registerErr(pattern, handler); err != nil {
2647 func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
2649 return errors.New("http: invalid pattern")
2652 return errors.New("http: nil handler")
2654 if f, ok := handler.(HandlerFunc); ok && f == nil {
2655 return errors.New("http: nil handler")
2658 pat, err := parsePattern(patstr)
2660 return fmt.Errorf("parsing %q: %w", patstr, err)
2663 // Get the caller's location, for better conflict error messages.
2664 // Skip register and whatever calls it.
2665 _, file, line, ok := runtime.Caller(3)
2667 pat.loc = "unknown location"
2669 pat.loc = fmt.Sprintf("%s:%d", file, line)
2673 defer mux.mu.Unlock()
2674 // Check for conflict.
2675 if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
2676 if pat.conflictsWith(pat2) {
2677 d := describeConflict(pat, pat2)
2678 return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
2679 pat, pat.loc, pat2, pat2.loc, d)
2685 mux.tree.addPattern(pat, handler)
2686 mux.index.addPattern(pat)
2687 mux.patterns = append(mux.patterns, pat)
2691 // Serve accepts incoming HTTP connections on the listener l,
2692 // creating a new service goroutine for each. The service goroutines
2693 // read requests and then call handler to reply to them.
2695 // The handler is typically nil, in which case [DefaultServeMux] is used.
2697 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
2698 // connections and they were configured with "h2" in the TLS
2699 // Config.NextProtos.
2701 // Serve always returns a non-nil error.
2702 func Serve(l net.Listener, handler Handler) error {
2703 srv := &Server{Handler: handler}
2707 // ServeTLS accepts incoming HTTPS connections on the listener l,
2708 // creating a new service goroutine for each. The service goroutines
2709 // read requests and then call handler to reply to them.
2711 // The handler is typically nil, in which case [DefaultServeMux] is used.
2713 // Additionally, files containing a certificate and matching private key
2714 // for the server must be provided. If the certificate is signed by a
2715 // certificate authority, the certFile should be the concatenation
2716 // of the server's certificate, any intermediates, and the CA's certificate.
2718 // ServeTLS always returns a non-nil error.
2719 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2720 srv := &Server{Handler: handler}
2721 return srv.ServeTLS(l, certFile, keyFile)
2724 // A Server defines parameters for running an HTTP server.
2725 // The zero value for Server is a valid configuration.
2726 type Server struct {
2727 // Addr optionally specifies the TCP address for the server to listen on,
2728 // in the form "host:port". If empty, ":http" (port 80) is used.
2729 // The service names are defined in RFC 6335 and assigned by IANA.
2730 // See net.Dial for details of the address format.
2733 Handler Handler // handler to invoke, http.DefaultServeMux if nil
2735 // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
2736 // otherwise responds with 200 OK and Content-Length: 0.
2737 DisableGeneralOptionsHandler bool
2739 // TLSConfig optionally provides a TLS configuration for use
2740 // by ServeTLS and ListenAndServeTLS. Note that this value is
2741 // cloned by ServeTLS and ListenAndServeTLS, so it's not
2742 // possible to modify the configuration with methods like
2743 // tls.Config.SetSessionTicketKeys. To use
2744 // SetSessionTicketKeys, use Server.Serve with a TLS Listener
2746 TLSConfig *tls.Config
2748 // ReadTimeout is the maximum duration for reading the entire
2749 // request, including the body. A zero or negative value means
2750 // there will be no timeout.
2752 // Because ReadTimeout does not let Handlers make per-request
2753 // decisions on each request body's acceptable deadline or
2754 // upload rate, most users will prefer to use
2755 // ReadHeaderTimeout. It is valid to use them both.
2756 ReadTimeout time.Duration
2758 // ReadHeaderTimeout is the amount of time allowed to read
2759 // request headers. The connection's read deadline is reset
2760 // after reading the headers and the Handler can decide what
2761 // is considered too slow for the body. If ReadHeaderTimeout
2762 // is zero, the value of ReadTimeout is used. If both are
2763 // zero, there is no timeout.
2764 ReadHeaderTimeout time.Duration
2766 // WriteTimeout is the maximum duration before timing out
2767 // writes of the response. It is reset whenever a new
2768 // request's header is read. Like ReadTimeout, it does not
2769 // let Handlers make decisions on a per-request basis.
2770 // A zero or negative value means there will be no timeout.
2771 WriteTimeout time.Duration
2773 // IdleTimeout is the maximum amount of time to wait for the
2774 // next request when keep-alives are enabled. If IdleTimeout
2775 // is zero, the value of ReadTimeout is used. If both are
2776 // zero, there is no timeout.
2777 IdleTimeout time.Duration
2779 // MaxHeaderBytes controls the maximum number of bytes the
2780 // server will read parsing the request header's keys and
2781 // values, including the request line. It does not limit the
2782 // size of the request body.
2783 // If zero, DefaultMaxHeaderBytes is used.
2786 // TLSNextProto optionally specifies a function to take over
2787 // ownership of the provided TLS connection when an ALPN
2788 // protocol upgrade has occurred. The map key is the protocol
2789 // name negotiated. The Handler argument should be used to
2790 // handle HTTP requests and will initialize the Request's TLS
2791 // and RemoteAddr if not already set. The connection is
2792 // automatically closed when the function returns.
2793 // If TLSNextProto is not nil, HTTP/2 support is not enabled
2795 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2797 // ConnState specifies an optional callback function that is
2798 // called when a client connection changes state. See the
2799 // ConnState type and associated constants for details.
2800 ConnState func(net.Conn, ConnState)
2802 // ErrorLog specifies an optional logger for errors accepting
2803 // connections, unexpected behavior from handlers, and
2804 // underlying FileSystem errors.
2805 // If nil, logging is done via the log package's standard logger.
2806 ErrorLog *log.Logger
2808 // BaseContext optionally specifies a function that returns
2809 // the base context for incoming requests on this server.
2810 // The provided Listener is the specific Listener that's
2811 // about to start accepting requests.
2812 // If BaseContext is nil, the default is context.Background().
2813 // If non-nil, it must return a non-nil context.
2814 BaseContext func(net.Listener) context.Context
2816 // ConnContext optionally specifies a function that modifies
2817 // the context used for a new connection c. The provided ctx
2818 // is derived from the base context and has a ServerContextKey
2820 ConnContext func(ctx context.Context, c net.Conn) context.Context
2822 inShutdown atomic.Bool // true when server is in shutdown
2824 disableKeepAlives atomic.Bool
2825 nextProtoOnce sync.Once // guards setupHTTP2_* init
2826 nextProtoErr error // result of http2.ConfigureServer if used
2829 listeners map[*net.Listener]struct{}
2830 activeConn map[*conn]struct{}
2833 listenerGroup sync.WaitGroup
2836 // Close immediately closes all active net.Listeners and any
2837 // connections in state StateNew, StateActive, or StateIdle. For a
2838 // graceful shutdown, use Shutdown.
2840 // Close does not attempt to close (and does not even know about)
2841 // any hijacked connections, such as WebSockets.
2843 // Close returns any error returned from closing the Server's
2844 // underlying Listener(s).
2845 func (srv *Server) Close() error {
2846 srv.inShutdown.Store(true)
2848 defer srv.mu.Unlock()
2849 err := srv.closeListenersLocked()
2851 // Unlock srv.mu while waiting for listenerGroup.
2852 // The group Add and Done calls are made with srv.mu held,
2853 // to avoid adding a new listener in the window between
2854 // us setting inShutdown above and waiting here.
2856 srv.listenerGroup.Wait()
2859 for c := range srv.activeConn {
2861 delete(srv.activeConn, c)
2866 // shutdownPollIntervalMax is the max polling interval when checking
2867 // quiescence during Server.Shutdown. Polling starts with a small
2868 // interval and backs off to the max.
2869 // Ideally we could find a solution that doesn't involve polling,
2870 // but which also doesn't have a high runtime cost (and doesn't
2871 // involve any contentious mutexes), but that is left as an
2872 // exercise for the reader.
2873 const shutdownPollIntervalMax = 500 * time.Millisecond
2875 // Shutdown gracefully shuts down the server without interrupting any
2876 // active connections. Shutdown works by first closing all open
2877 // listeners, then closing all idle connections, and then waiting
2878 // indefinitely for connections to return to idle and then shut down.
2879 // If the provided context expires before the shutdown is complete,
2880 // Shutdown returns the context's error, otherwise it returns any
2881 // error returned from closing the Server's underlying Listener(s).
2883 // When Shutdown is called, Serve, ListenAndServe, and
2884 // ListenAndServeTLS immediately return ErrServerClosed. Make sure the
2885 // program doesn't exit and waits instead for Shutdown to return.
2887 // Shutdown does not attempt to close nor wait for hijacked
2888 // connections such as WebSockets. The caller of Shutdown should
2889 // separately notify such long-lived connections of shutdown and wait
2890 // for them to close, if desired. See RegisterOnShutdown for a way to
2891 // register shutdown notification functions.
2893 // Once Shutdown has been called on a server, it may not be reused;
2894 // future calls to methods such as Serve will return ErrServerClosed.
2895 func (srv *Server) Shutdown(ctx context.Context) error {
2896 srv.inShutdown.Store(true)
2899 lnerr := srv.closeListenersLocked()
2900 for _, f := range srv.onShutdown {
2904 srv.listenerGroup.Wait()
2906 pollIntervalBase := time.Millisecond
2907 nextPollInterval := func() time.Duration {
2909 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
2910 // Double and clamp for next time.
2911 pollIntervalBase *= 2
2912 if pollIntervalBase > shutdownPollIntervalMax {
2913 pollIntervalBase = shutdownPollIntervalMax
2918 timer := time.NewTimer(nextPollInterval())
2921 if srv.closeIdleConns() {
2928 timer.Reset(nextPollInterval())
2933 // RegisterOnShutdown registers a function to call on Shutdown.
2934 // This can be used to gracefully shutdown connections that have
2935 // undergone ALPN protocol upgrade or that have been hijacked.
2936 // This function should start protocol-specific graceful shutdown,
2937 // but should not wait for shutdown to complete.
2938 func (srv *Server) RegisterOnShutdown(f func()) {
2940 srv.onShutdown = append(srv.onShutdown, f)
2944 // closeIdleConns closes all idle connections and reports whether the
2945 // server is quiescent.
2946 func (s *Server) closeIdleConns() bool {
2950 for c := range s.activeConn {
2951 st, unixSec := c.getState()
2952 // Issue 22682: treat StateNew connections as if
2953 // they're idle if we haven't read the first request's
2954 // header in over 5 seconds.
2955 if st == StateNew && unixSec < time.Now().Unix()-5 {
2958 if st != StateIdle || unixSec == 0 {
2959 // Assume unixSec == 0 means it's a very new
2960 // connection, without state set yet.
2965 delete(s.activeConn, c)
2970 func (s *Server) closeListenersLocked() error {
2972 for ln := range s.listeners {
2973 if cerr := (*ln).Close(); cerr != nil && err == nil {
2980 // A ConnState represents the state of a client connection to a server.
2981 // It's used by the optional Server.ConnState hook.
2985 // StateNew represents a new connection that is expected to
2986 // send a request immediately. Connections begin at this
2987 // state and then transition to either StateActive or
2989 StateNew ConnState = iota
2991 // StateActive represents a connection that has read 1 or more
2992 // bytes of a request. The Server.ConnState hook for
2993 // StateActive fires before the request has entered a handler
2994 // and doesn't fire again until the request has been
2995 // handled. After the request is handled, the state
2996 // transitions to StateClosed, StateHijacked, or StateIdle.
2997 // For HTTP/2, StateActive fires on the transition from zero
2998 // to one active request, and only transitions away once all
2999 // active requests are complete. That means that ConnState
3000 // cannot be used to do per-request work; ConnState only notes
3001 // the overall state of the connection.
3004 // StateIdle represents a connection that has finished
3005 // handling a request and is in the keep-alive state, waiting
3006 // for a new request. Connections transition from StateIdle
3007 // to either StateActive or StateClosed.
3010 // StateHijacked represents a hijacked connection.
3011 // This is a terminal state. It does not transition to StateClosed.
3014 // StateClosed represents a closed connection.
3015 // This is a terminal state. Hijacked connections do not
3016 // transition to StateClosed.
3020 var stateName = map[ConnState]string{
3022 StateActive: "active",
3024 StateHijacked: "hijacked",
3025 StateClosed: "closed",
3028 func (c ConnState) String() string {
3032 // serverHandler delegates to either the server's Handler or
3033 // DefaultServeMux and also handles "OPTIONS *" requests.
3034 type serverHandler struct {
3038 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
3039 handler := sh.srv.Handler
3041 handler = DefaultServeMux
3043 if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
3044 handler = globalOptionsHandler{}
3047 handler.ServeHTTP(rw, req)
3050 // AllowQuerySemicolons returns a handler that serves requests by converting any
3051 // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
3053 // This restores the pre-Go 1.17 behavior of splitting query parameters on both
3054 // semicolons and ampersands. (See golang.org/issue/25192). Note that this
3055 // behavior doesn't match that of many proxies, and the mismatch can lead to
3058 // AllowQuerySemicolons should be invoked before Request.ParseForm is called.
3059 func AllowQuerySemicolons(h Handler) Handler {
3060 return HandlerFunc(func(w ResponseWriter, r *Request) {
3061 if strings.Contains(r.URL.RawQuery, ";") {
3064 r2.URL = new(url.URL)
3066 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
3074 // ListenAndServe listens on the TCP network address srv.Addr and then
3075 // calls Serve to handle requests on incoming connections.
3076 // Accepted connections are configured to enable TCP keep-alives.
3078 // If srv.Addr is blank, ":http" is used.
3080 // ListenAndServe always returns a non-nil error. After Shutdown or Close,
3081 // the returned error is ErrServerClosed.
3082 func (srv *Server) ListenAndServe() error {
3083 if srv.shuttingDown() {
3084 return ErrServerClosed
3090 ln, err := net.Listen("tcp", addr)
3094 return srv.Serve(ln)
3097 var testHookServerServe func(*Server, net.Listener) // used if non-nil
3099 // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
3100 // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
3101 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
3102 if srv.TLSConfig == nil {
3103 // Compatibility with Go 1.6:
3104 // If there's no TLSConfig, it's possible that the user just
3105 // didn't set it on the http.Server, but did pass it to
3106 // tls.NewListener and passed that listener to Serve.
3107 // So we should configure HTTP/2 (to set up srv.TLSNextProto)
3108 // in case the listener returns an "h2" *tls.Conn.
3111 // The user specified a TLSConfig on their http.Server.
3112 // In this, case, only configure HTTP/2 if their tls.Config
3113 // explicitly mentions "h2". Otherwise http2.ConfigureServer
3114 // would modify the tls.Config to add it, but they probably already
3115 // passed this tls.Config to tls.NewListener. And if they did,
3116 // it's too late anyway to fix it. It would only be potentially racy.
3118 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
3121 // ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
3122 // and ListenAndServeTLS methods after a call to Shutdown or Close.
3123 var ErrServerClosed = errors.New("http: Server closed")
3125 // Serve accepts incoming connections on the Listener l, creating a
3126 // new service goroutine for each. The service goroutines read requests and
3127 // then call srv.Handler to reply to them.
3129 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
3130 // connections and they were configured with "h2" in the TLS
3131 // Config.NextProtos.
3133 // Serve always returns a non-nil error and closes l.
3134 // After Shutdown or Close, the returned error is ErrServerClosed.
3135 func (srv *Server) Serve(l net.Listener) error {
3136 if fn := testHookServerServe; fn != nil {
3137 fn(srv, l) // call hook with unwrapped listener
3141 l = &onceCloseListener{Listener: l}
3144 if err := srv.setupHTTP2_Serve(); err != nil {
3148 if !srv.trackListener(&l, true) {
3149 return ErrServerClosed
3151 defer srv.trackListener(&l, false)
3153 baseCtx := context.Background()
3154 if srv.BaseContext != nil {
3155 baseCtx = srv.BaseContext(origListener)
3157 panic("BaseContext returned a nil context")
3161 var tempDelay time.Duration // how long to sleep on accept failure
3163 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3165 rw, err := l.Accept()
3167 if srv.shuttingDown() {
3168 return ErrServerClosed
3170 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3172 tempDelay = 5 * time.Millisecond
3176 if max := 1 * time.Second; tempDelay > max {
3179 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3180 time.Sleep(tempDelay)
3186 if cc := srv.ConnContext; cc != nil {
3187 connCtx = cc(connCtx, rw)
3189 panic("ConnContext returned nil")
3193 c := srv.newConn(rw)
3194 c.setState(c.rwc, StateNew, runHooks) // before Serve can return
3199 // ServeTLS accepts incoming connections on the Listener l, creating a
3200 // new service goroutine for each. The service goroutines perform TLS
3201 // setup and then read requests, calling srv.Handler to reply to them.
3203 // Files containing a certificate and matching private key for the
3204 // server must be provided if neither the Server's
3205 // TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
3206 // If the certificate is signed by a certificate authority, the
3207 // certFile should be the concatenation of the server's certificate,
3208 // any intermediates, and the CA's certificate.
3210 // ServeTLS always returns a non-nil error. After Shutdown or Close, the
3211 // returned error is ErrServerClosed.
3212 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3213 // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
3214 // before we clone it and create the TLS Listener.
3215 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3219 config := cloneTLSConfig(srv.TLSConfig)
3220 if !strSliceContains(config.NextProtos, "http/1.1") {
3221 config.NextProtos = append(config.NextProtos, "http/1.1")
3224 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3225 if !configHasCert || certFile != "" || keyFile != "" {
3227 config.Certificates = make([]tls.Certificate, 1)
3228 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3234 tlsListener := tls.NewListener(l, config)
3235 return srv.Serve(tlsListener)
3238 // trackListener adds or removes a net.Listener to the set of tracked
3241 // We store a pointer to interface in the map set, in case the
3242 // net.Listener is not comparable. This is safe because we only call
3243 // trackListener via Serve and can track+defer untrack the same
3244 // pointer to local variable there. We never need to compare a
3245 // Listener from another caller.
3247 // It reports whether the server is still up (not Shutdown or Closed).
3248 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3251 if s.listeners == nil {
3252 s.listeners = make(map[*net.Listener]struct{})
3255 if s.shuttingDown() {
3258 s.listeners[ln] = struct{}{}
3259 s.listenerGroup.Add(1)
3261 delete(s.listeners, ln)
3262 s.listenerGroup.Done()
3267 func (s *Server) trackConn(c *conn, add bool) {
3270 if s.activeConn == nil {
3271 s.activeConn = make(map[*conn]struct{})
3274 s.activeConn[c] = struct{}{}
3276 delete(s.activeConn, c)
3280 func (s *Server) idleTimeout() time.Duration {
3281 if s.IdleTimeout != 0 {
3282 return s.IdleTimeout
3284 return s.ReadTimeout
3287 func (s *Server) readHeaderTimeout() time.Duration {
3288 if s.ReadHeaderTimeout != 0 {
3289 return s.ReadHeaderTimeout
3291 return s.ReadTimeout
3294 func (s *Server) doKeepAlives() bool {
3295 return !s.disableKeepAlives.Load() && !s.shuttingDown()
3298 func (s *Server) shuttingDown() bool {
3299 return s.inShutdown.Load()
3302 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
3303 // By default, keep-alives are always enabled. Only very
3304 // resource-constrained environments or servers in the process of
3305 // shutting down should disable them.
3306 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3308 srv.disableKeepAlives.Store(false)
3311 srv.disableKeepAlives.Store(true)
3313 // Close idle HTTP/1 conns:
3314 srv.closeIdleConns()
3316 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
3319 func (s *Server) logf(format string, args ...any) {
3320 if s.ErrorLog != nil {
3321 s.ErrorLog.Printf(format, args...)
3323 log.Printf(format, args...)
3327 // logf prints to the ErrorLog of the *Server associated with request r
3328 // via ServerContextKey. If there's no associated server, or if ErrorLog
3329 // is nil, logging is done via the log package's standard logger.
3330 func logf(r *Request, format string, args ...any) {
3331 s, _ := r.Context().Value(ServerContextKey).(*Server)
3332 if s != nil && s.ErrorLog != nil {
3333 s.ErrorLog.Printf(format, args...)
3335 log.Printf(format, args...)
3339 // ListenAndServe listens on the TCP network address addr and then calls
3340 // Serve with handler to handle requests on incoming connections.
3341 // Accepted connections are configured to enable TCP keep-alives.
3343 // The handler is typically nil, in which case [DefaultServeMux] is used.
3345 // ListenAndServe always returns a non-nil error.
3346 func ListenAndServe(addr string, handler Handler) error {
3347 server := &Server{Addr: addr, Handler: handler}
3348 return server.ListenAndServe()
3351 // ListenAndServeTLS acts identically to [ListenAndServe], except that it
3352 // expects HTTPS connections. Additionally, files containing a certificate and
3353 // matching private key for the server must be provided. If the certificate
3354 // is signed by a certificate authority, the certFile should be the concatenation
3355 // of the server's certificate, any intermediates, and the CA's certificate.
3356 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3357 server := &Server{Addr: addr, Handler: handler}
3358 return server.ListenAndServeTLS(certFile, keyFile)
3361 // ListenAndServeTLS listens on the TCP network address srv.Addr and
3362 // then calls ServeTLS to handle requests on incoming TLS connections.
3363 // Accepted connections are configured to enable TCP keep-alives.
3365 // Filenames containing a certificate and matching private key for the
3366 // server must be provided if neither the Server's TLSConfig.Certificates
3367 // nor TLSConfig.GetCertificate are populated. If the certificate is
3368 // signed by a certificate authority, the certFile should be the
3369 // concatenation of the server's certificate, any intermediates, and
3370 // the CA's certificate.
3372 // If srv.Addr is blank, ":https" is used.
3374 // ListenAndServeTLS always returns a non-nil error. After Shutdown or
3375 // Close, the returned error is ErrServerClosed.
3376 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3377 if srv.shuttingDown() {
3378 return ErrServerClosed
3385 ln, err := net.Listen("tcp", addr)
3392 return srv.ServeTLS(ln, certFile, keyFile)
3395 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
3396 // srv and reports whether there was an error setting it up. If it is
3397 // not configured for policy reasons, nil is returned.
3398 func (srv *Server) setupHTTP2_ServeTLS() error {
3399 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3400 return srv.nextProtoErr
3403 // setupHTTP2_Serve is called from (*Server).Serve and conditionally
3404 // configures HTTP/2 on srv using a more conservative policy than
3405 // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
3406 // and may be called concurrently. See shouldConfigureHTTP2ForServe.
3408 // The tests named TestTransportAutomaticHTTP2* and
3409 // TestConcurrentServerServe in server_test.go demonstrate some
3410 // of the supported use cases and motivations.
3411 func (srv *Server) setupHTTP2_Serve() error {
3412 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3413 return srv.nextProtoErr
3416 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3417 if srv.shouldConfigureHTTP2ForServe() {
3418 srv.onceSetNextProtoDefaults()
3422 var http2server = godebug.New("http2server")
3424 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
3425 // configured otherwise. (by setting srv.TLSNextProto non-nil)
3426 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
3427 func (srv *Server) onceSetNextProtoDefaults() {
3428 if omitBundledHTTP2 {
3431 if http2server.Value() == "0" {
3432 http2server.IncNonDefault()
3435 // Enable HTTP/2 by default if the user hasn't otherwise
3436 // configured their TLSNextProto map.
3437 if srv.TLSNextProto == nil {
3438 conf := &http2Server{
3439 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3441 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3445 // TimeoutHandler returns a Handler that runs h with the given time limit.
3447 // The new Handler calls h.ServeHTTP to handle each request, but if a
3448 // call runs for longer than its time limit, the handler responds with
3449 // a 503 Service Unavailable error and the given message in its body.
3450 // (If msg is empty, a suitable default message will be sent.)
3451 // After such a timeout, writes by h to its ResponseWriter will return
3452 // ErrHandlerTimeout.
3454 // TimeoutHandler supports the Pusher interface but does not support
3455 // the Hijacker or Flusher interfaces.
3456 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3457 return &timeoutHandler{
3464 // ErrHandlerTimeout is returned on ResponseWriter Write calls
3465 // in handlers which have timed out.
3466 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3468 type timeoutHandler struct {
3473 // When set, no context will be created and this context will
3475 testContext context.Context
3478 func (h *timeoutHandler) errorBody() string {
3482 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3485 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3486 ctx := h.testContext
3488 var cancelCtx context.CancelFunc
3489 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3492 r = r.WithContext(ctx)
3493 done := make(chan struct{})
3494 tw := &timeoutWriter{
3499 panicChan := make(chan any, 1)
3502 if p := recover(); p != nil {
3506 h.handler.ServeHTTP(tw, r)
3510 case p := <-panicChan:
3514 defer tw.mu.Unlock()
3516 for k, vv := range tw.h {
3519 if !tw.wroteHeader {
3522 w.WriteHeader(tw.code)
3523 w.Write(tw.wbuf.Bytes())
3526 defer tw.mu.Unlock()
3527 switch err := ctx.Err(); err {
3528 case context.DeadlineExceeded:
3529 w.WriteHeader(StatusServiceUnavailable)
3530 io.WriteString(w, h.errorBody())
3531 tw.err = ErrHandlerTimeout
3533 w.WriteHeader(StatusServiceUnavailable)
3539 type timeoutWriter struct {
3551 var _ Pusher = (*timeoutWriter)(nil)
3553 // Push implements the Pusher interface.
3554 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3555 if pusher, ok := tw.w.(Pusher); ok {
3556 return pusher.Push(target, opts)
3558 return ErrNotSupported
3561 func (tw *timeoutWriter) Header() Header { return tw.h }
3563 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3565 defer tw.mu.Unlock()
3569 if !tw.wroteHeader {
3570 tw.writeHeaderLocked(StatusOK)
3572 return tw.wbuf.Write(p)
3575 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3576 checkWriteHeaderCode(code)
3581 case tw.wroteHeader:
3583 caller := relevantCaller()
3584 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3587 tw.wroteHeader = true
3592 func (tw *timeoutWriter) WriteHeader(code int) {
3594 defer tw.mu.Unlock()
3595 tw.writeHeaderLocked(code)
3598 // onceCloseListener wraps a net.Listener, protecting it from
3599 // multiple Close calls.
3600 type onceCloseListener struct {
3606 func (oc *onceCloseListener) Close() error {
3607 oc.once.Do(oc.close)
3611 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3613 // globalOptionsHandler responds to "OPTIONS *" requests.
3614 type globalOptionsHandler struct{}
3616 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3617 w.Header().Set("Content-Length", "0")
3618 if r.ContentLength != 0 {
3619 // Read up to 4KB of OPTIONS body (as mentioned in the
3620 // spec as being reserved for future use), but anything
3621 // over that is considered a waste of server resources
3622 // (or an attack) and we abort and close the connection,
3623 // courtesy of MaxBytesReader's EOF behavior.
3624 mb := MaxBytesReader(w, r.Body, 4<<10)
3625 io.Copy(io.Discard, mb)
3629 // initALPNRequest is an HTTP handler that initializes certain
3630 // uninitialized fields in its *Request. Such partially-initialized
3631 // Requests come from ALPN protocol handlers.
3632 type initALPNRequest struct {
3638 // BaseContext is an exported but unadvertised http.Handler method
3639 // recognized by x/net/http2 to pass down a context; the TLSNextProto
3640 // API predates context support so we shoehorn through the only
3641 // interface we have available.
3642 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3644 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3646 req.TLS = &tls.ConnectionState{}
3647 *req.TLS = h.c.ConnectionState()
3649 if req.Body == nil {
3652 if req.RemoteAddr == "" {
3653 req.RemoteAddr = h.c.RemoteAddr().String()
3655 h.h.ServeHTTP(rw, req)
3658 // loggingConn is used for debugging.
3659 type loggingConn struct {
3665 uniqNameMu sync.Mutex
3666 uniqNameNext = make(map[string]int)
3669 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3671 defer uniqNameMu.Unlock()
3672 uniqNameNext[baseName]++
3673 return &loggingConn{
3674 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3679 func (c *loggingConn) Write(p []byte) (n int, err error) {
3680 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3681 n, err = c.Conn.Write(p)
3682 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3686 func (c *loggingConn) Read(p []byte) (n int, err error) {
3687 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3688 n, err = c.Conn.Read(p)
3689 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3693 func (c *loggingConn) Close() (err error) {
3694 log.Printf("%s.Close() = ...", c.name)
3695 err = c.Conn.Close()
3696 log.Printf("%s.Close() = %v", c.name, err)
3700 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
3701 // It only contains one field (and a pointer field at that), so it
3702 // fits in an interface value without an extra allocation.
3703 type checkConnErrorWriter struct {
3707 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3708 n, err = w.c.rwc.Write(p)
3709 if err != nil && w.c.werr == nil {
3716 func numLeadingCRorLF(v []byte) (n int) {
3717 for _, b := range v {
3718 if b == '\r' || b == '\n' {
3728 func strSliceContains(ss []string, s string) bool {
3729 for _, v := range ss {
3737 // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
3738 // looks like it might've been a misdirected plaintext HTTP request.
3739 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3740 switch string(hdr[:]) {
3741 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3747 // MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.
3748 func MaxBytesHandler(h Handler, n int64) Handler {
3749 return HandlerFunc(func(w ResponseWriter, r *Request) {
3751 r2.Body = MaxBytesReader(w, r.Body, n)