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.
32 "golang.org/x/net/http/httpguts"
35 // Errors used by the HTTP server.
37 // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
38 // when the HTTP method or response code does not permit a
40 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
42 // ErrHijacked is returned by ResponseWriter.Write calls when
43 // the underlying connection has been hijacked using the
44 // Hijacker interface. A zero-byte write on a hijacked
45 // connection will return ErrHijacked without any other side
47 ErrHijacked = errors.New("http: connection has been hijacked")
49 // ErrContentLength is returned by ResponseWriter.Write calls
50 // when a Handler set a Content-Length response header with a
51 // declared size and then attempted to write more bytes than
53 ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
55 // Deprecated: ErrWriteAfterFlush is no longer returned by
56 // anything in the net/http package. Callers should not
57 // compare errors against this variable.
58 ErrWriteAfterFlush = errors.New("unused")
61 // A Handler responds to an HTTP request.
63 // ServeHTTP should write reply headers and data to the [ResponseWriter]
64 // and then return. Returning signals that the request is finished; it
65 // is not valid to use the [ResponseWriter] or read from the
66 // [Request.Body] after or concurrently with the completion of the
69 // Depending on the HTTP client software, HTTP protocol version, and
70 // any intermediaries between the client and the Go server, it may not
71 // be possible to read from the [Request.Body] after writing to the
72 // [ResponseWriter]. Cautious handlers should read the [Request.Body]
73 // first, and then reply.
75 // Except for reading the body, handlers should not modify the
78 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
79 // that the effect of the panic was isolated to the active request.
80 // It recovers the panic, logs a stack trace to the server error log,
81 // and either closes the network connection or sends an HTTP/2
82 // RST_STREAM, depending on the HTTP protocol. To abort a handler so
83 // the client sees an interrupted response but the server doesn't log
84 // an error, panic with the value [ErrAbortHandler].
85 type Handler interface {
86 ServeHTTP(ResponseWriter, *Request)
89 // A ResponseWriter interface is used by an HTTP handler to
90 // construct an HTTP response.
92 // A ResponseWriter may not be used after [Handler.ServeHTTP] has returned.
93 type ResponseWriter interface {
94 // Header returns the header map that will be sent by
95 // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
96 // [Handler] implementations can set HTTP trailers.
98 // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
99 // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
100 // 1xx class or the modified headers are trailers.
102 // There are two ways to set Trailers. The preferred way is to
103 // predeclare in the headers which trailers you will later
104 // send by setting the "Trailer" header to the names of the
105 // trailer keys which will come later. In this case, those
106 // keys of the Header map are treated as if they were
107 // trailers. See the example. The second way, for trailer
108 // keys not known to the [Handler] until after the first [ResponseWriter.Write],
109 // is to prefix the [Header] map keys with the [TrailerPrefix]
112 // To suppress automatic response headers (such as "Date"), set
113 // their value to nil.
116 // Write writes the data to the connection as part of an HTTP reply.
118 // If [ResponseWriter.WriteHeader] has not yet been called, Write calls
119 // WriteHeader(http.StatusOK) before writing the data. If the Header
120 // does not contain a Content-Type line, Write adds a Content-Type set
121 // to the result of passing the initial 512 bytes of written data to
122 // [DetectContentType]. Additionally, if the total size of all written
123 // data is under a few KB and there are no Flush calls, the
124 // Content-Length header is added automatically.
126 // Depending on the HTTP protocol version and the client, calling
127 // Write or WriteHeader may prevent future reads on the
128 // Request.Body. For HTTP/1.x requests, handlers should read any
129 // needed request body data before writing the response. Once the
130 // headers have been flushed (due to either an explicit Flusher.Flush
131 // call or writing enough data to trigger a flush), the request body
132 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
133 // handlers to continue to read the request body while concurrently
134 // writing the response. However, such behavior may not be supported
135 // by all HTTP/2 clients. Handlers should read before writing if
136 // possible to maximize compatibility.
137 Write([]byte) (int, error)
139 // WriteHeader sends an HTTP response header with the provided
142 // If WriteHeader is not called explicitly, the first call to Write
143 // will trigger an implicit WriteHeader(http.StatusOK).
144 // Thus explicit calls to WriteHeader are mainly used to
145 // send error codes or 1xx informational responses.
147 // The provided code must be a valid HTTP 1xx-5xx status code.
148 // Any number of 1xx headers may be written, followed by at most
149 // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
150 // headers may be buffered. Use the Flusher interface to send
151 // buffered data. The header map is cleared when 2xx-5xx headers are
152 // sent, but not with 1xx headers.
154 // The server will automatically send a 100 (Continue) header
155 // on the first read from the request body if the request has
156 // an "Expect: 100-continue" header.
157 WriteHeader(statusCode int)
160 // The Flusher interface is implemented by ResponseWriters that allow
161 // an HTTP handler to flush buffered data to the client.
163 // The default HTTP/1.x and HTTP/2 ResponseWriter implementations
164 // support Flusher, but ResponseWriter wrappers may not. Handlers
165 // should always test for this ability at runtime.
167 // Note that even for ResponseWriters that support Flush,
168 // if the client is connected through an HTTP proxy,
169 // the buffered data may not reach the client until the response
171 type Flusher interface {
172 // Flush sends any buffered data to the client.
176 // The Hijacker interface is implemented by ResponseWriters that allow
177 // an HTTP handler to take over the connection.
179 // The default ResponseWriter for HTTP/1.x connections supports
180 // Hijacker, but HTTP/2 connections intentionally do not.
181 // ResponseWriter wrappers may also not support Hijacker. Handlers
182 // should always test for this ability at runtime.
183 type Hijacker interface {
184 // Hijack lets the caller take over the connection.
185 // After a call to Hijack the HTTP server library
186 // will not do anything else with the connection.
188 // It becomes the caller's responsibility to manage
189 // and close the connection.
191 // The returned net.Conn may have read or write deadlines
192 // already set, depending on the configuration of the
193 // Server. It is the caller's responsibility to set
194 // or clear those deadlines as needed.
196 // The returned bufio.Reader may contain unprocessed buffered
197 // data from the client.
199 // After a call to Hijack, the original Request.Body must not
200 // be used. The original Request's Context remains valid and
201 // is not canceled until the Request's ServeHTTP method
203 Hijack() (net.Conn, *bufio.ReadWriter, error)
206 // The CloseNotifier interface is implemented by ResponseWriters which
207 // allow detecting when the underlying connection has gone away.
209 // This mechanism can be used to cancel long operations on the server
210 // if the client has disconnected before the response is ready.
212 // Deprecated: the CloseNotifier interface predates Go's context package.
213 // New code should use Request.Context instead.
214 type CloseNotifier interface {
215 // CloseNotify returns a channel that receives at most a
216 // single value (true) when the client connection has gone
219 // CloseNotify may wait to notify until Request.Body has been
222 // After the Handler has returned, there is no guarantee
223 // that the channel receives a value.
225 // If the protocol is HTTP/1.1 and CloseNotify is called while
226 // processing an idempotent request (such a GET) while
227 // HTTP/1.1 pipelining is in use, the arrival of a subsequent
228 // pipelined request may cause a value to be sent on the
229 // returned channel. In practice HTTP/1.1 pipelining is not
230 // enabled in browsers and not seen often in the wild. If this
231 // is a problem, use HTTP/2 or only use CloseNotify on methods
233 CloseNotify() <-chan bool
237 // ServerContextKey is a context key. It can be used in HTTP
238 // handlers with Context.Value to access the server that
239 // started the handler. The associated value will be of
241 ServerContextKey = &contextKey{"http-server"}
243 // LocalAddrContextKey is a context key. It can be used in
244 // HTTP handlers with Context.Value to access the local
245 // address the connection arrived on.
246 // The associated value will be of type net.Addr.
247 LocalAddrContextKey = &contextKey{"local-addr"}
250 // A conn represents the server side of an HTTP connection.
252 // server is the server on which the connection arrived.
253 // Immutable; never nil.
256 // cancelCtx cancels the connection-level context.
257 cancelCtx context.CancelFunc
259 // rwc is the underlying network connection.
260 // This is never wrapped by other types and is the value given out
261 // to CloseNotifier callers. It is usually of type *net.TCPConn or
265 // remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
266 // inside the Listener's Accept goroutine, as some implementations block.
267 // It is populated immediately inside the (*conn).serve goroutine.
268 // This is the value of a Handler's (*Request).RemoteAddr.
271 // tlsState is the TLS connection state when using TLS.
272 // nil means not TLS.
273 tlsState *tls.ConnectionState
275 // werr is set to the first write error to rwc.
276 // It is set via checkConnErrorWriter{w}, where bufw writes.
279 // r is bufr's read source. It's a wrapper around rwc that provides
280 // io.LimitedReader-style limiting (while reading request headers)
281 // and functionality to support CloseNotifier. See *connReader docs.
284 // bufr reads from r.
287 // bufw writes to checkConnErrorWriter{c}, which populates werr on error.
290 // lastMethod is the method of the most recent request
291 // on this connection, if any.
294 curReq atomic.Pointer[response] // (which has a Request in it)
296 curState atomic.Uint64 // packed (unixtime<<8|uint8(ConnState))
298 // mu guards hijackedv
301 // hijackedv is whether this connection has been hijacked
302 // by a Handler with the Hijacker interface.
303 // It is guarded by mu.
307 func (c *conn) hijacked() bool {
313 // c.mu must be held.
314 func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
316 return nil, nil, ErrHijacked
318 c.r.abortPendingRead()
322 rwc.SetDeadline(time.Time{})
324 buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
326 if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
327 return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
330 c.setState(rwc, StateHijacked, runHooks)
334 // This should be >= 512 bytes for DetectContentType,
335 // but otherwise it's somewhat arbitrary.
336 const bufferBeforeChunkingSize = 2048
338 // chunkWriter writes to a response's conn buffer, and is the writer
339 // wrapped by the response.w buffered writer.
341 // chunkWriter also is responsible for finalizing the Header, including
342 // conditionally setting the Content-Type and setting a Content-Length
343 // in cases where the handler's final output is smaller than the buffer
344 // size. It also conditionally adds chunk headers, when in chunking mode.
346 // See the comment above (*response).Write for the entire write flow.
347 type chunkWriter struct {
350 // header is either nil or a deep clone of res.handlerHeader
351 // at the time of res.writeHeader, if res.writeHeader is
352 // called and extra buffering is being done to calculate
353 // Content-Type and/or Content-Length.
356 // wroteHeader tells whether the header's been written to "the
357 // wire" (or rather: w.conn.buf). this is unlike
358 // (*response).wroteHeader, which tells only whether it was
359 // logically written.
362 // set by the writeHeader method:
363 chunking bool // using chunked transfer encoding for reply body
367 crlf = []byte("\r\n")
368 colonSpace = []byte(": ")
371 func (cw *chunkWriter) Write(p []byte) (n int, err error) {
375 if cw.res.req.Method == "HEAD" {
380 _, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
382 cw.res.conn.rwc.Close()
386 n, err = cw.res.conn.bufw.Write(p)
387 if cw.chunking && err == nil {
388 _, err = cw.res.conn.bufw.Write(crlf)
391 cw.res.conn.rwc.Close()
396 func (cw *chunkWriter) flush() error {
400 return cw.res.conn.bufw.Flush()
403 func (cw *chunkWriter) close() {
408 bw := cw.res.conn.bufw // conn's bufio writer
409 // zero chunk to mark EOF
410 bw.WriteString("0\r\n")
411 if trailers := cw.res.finalTrailers(); trailers != nil {
412 trailers.Write(bw) // the writer handles noting errors
414 // final blank line after the trailers (whether
416 bw.WriteString("\r\n")
420 // A response represents the server side of an HTTP response.
421 type response struct {
423 req *Request // request for this response
424 reqBody io.ReadCloser
425 cancelCtx context.CancelFunc // when ServeHTTP exits
426 wroteHeader bool // a non-1xx header has been (logically) written
427 wroteContinue bool // 100 Continue response was written
428 wants10KeepAlive bool // HTTP/1.0 w/ Connection "keep-alive"
429 wantsClose bool // HTTP request has Connection "close"
431 // canWriteContinue is an atomic boolean that says whether or
432 // not a 100 Continue header can be written to the
434 // writeContinueMu must be held while writing the header.
435 // These two fields together synchronize the body reader (the
436 // expectContinueReader, which wants to write 100 Continue)
437 // against the main writer.
438 canWriteContinue atomic.Bool
439 writeContinueMu sync.Mutex
441 w *bufio.Writer // buffers output in chunks to chunkWriter
444 // handlerHeader is the Header that Handlers get access to,
445 // which may be retained and mutated even after WriteHeader.
446 // handlerHeader is copied into cw.header at WriteHeader
447 // time, and privately mutated thereafter.
449 calledHeader bool // handler accessed handlerHeader via Header
451 written int64 // number of bytes written in body
452 contentLength int64 // explicitly-declared Content-Length; or -1
453 status int // status code passed to WriteHeader
455 // close connection after this reply. set on request and
456 // updated after response from handler if there's a
457 // "Connection: keep-alive" response header and a
461 // When fullDuplex is false (the default), we consume any remaining
462 // request body before starting to write a response.
465 // requestBodyLimitHit is set by requestTooLarge when
466 // maxBytesReader hits its max size. It is checked in
467 // WriteHeader, to make sure we don't consume the
468 // remaining request body to try to advance to the next HTTP
469 // request. Instead, when this is set, we stop reading
470 // subsequent requests on this connection and stop reading
472 requestBodyLimitHit bool
474 // trailers are the headers to be sent after the handler
475 // finishes writing the body. This field is initialized from
476 // the Trailer response header when the response header is
480 handlerDone atomic.Bool // set true when the handler exits
482 // Buffers for Date, Content-Length, and status code
483 dateBuf [len(TimeFormat)]byte
487 // closeNotifyCh is the channel returned by CloseNotify.
488 // TODO(bradfitz): this is currently (for Go 1.8) always
489 // non-nil. Make this lazily-created again as it used to be?
490 closeNotifyCh chan bool
491 didCloseNotify atomic.Bool // atomic (only false->true winner should send)
494 func (c *response) SetReadDeadline(deadline time.Time) error {
495 return c.conn.rwc.SetReadDeadline(deadline)
498 func (c *response) SetWriteDeadline(deadline time.Time) error {
499 return c.conn.rwc.SetWriteDeadline(deadline)
502 func (c *response) EnableFullDuplex() error {
507 // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
508 // that, if present, signals that the map entry is actually for
509 // the response trailers, and not the response headers. The prefix
510 // is stripped after the ServeHTTP call finishes and the values are
511 // sent in the trailers.
513 // This mechanism is intended only for trailers that are not known
514 // prior to the headers being written. If the set of trailers is fixed
515 // or known before the header is written, the normal Go trailers mechanism
518 // https://pkg.go.dev/net/http#ResponseWriter
519 // https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
520 const TrailerPrefix = "Trailer:"
522 // finalTrailers is called after the Handler exits and returns a non-nil
523 // value if the Handler set any trailers.
524 func (w *response) finalTrailers() Header {
526 for k, vv := range w.handlerHeader {
527 if kk, found := strings.CutPrefix(k, TrailerPrefix); found {
534 for _, k := range w.trailers {
538 for _, v := range w.handlerHeader[k] {
545 // declareTrailer is called for each Trailer header when the
546 // response header is written. It notes that a header will need to be
547 // written in the trailers at the end of the response.
548 func (w *response) declareTrailer(k string) {
549 k = CanonicalHeaderKey(k)
550 if !httpguts.ValidTrailerHeader(k) {
551 // Forbidden by RFC 7230, section 4.1.2
554 w.trailers = append(w.trailers, k)
557 // requestTooLarge is called by maxBytesReader when too much input has
558 // been read from the client.
559 func (w *response) requestTooLarge() {
560 w.closeAfterReply = true
561 w.requestBodyLimitHit = true
563 w.Header().Set("Connection", "close")
567 // writerOnly hides an io.Writer value's optional ReadFrom method
569 type writerOnly struct {
573 // ReadFrom is here to optimize copying from an *os.File regular file
574 // to a *net.TCPConn with sendfile, or from a supported src type such
575 // as a *net.TCPConn on Linux with splice.
576 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
577 bufp := copyBufPool.Get().(*[]byte)
579 defer copyBufPool.Put(bufp)
581 // Our underlying w.conn.rwc is usually a *TCPConn (with its
582 // own ReadFrom method). If not, just fall back to the normal
584 rf, ok := w.conn.rwc.(io.ReaderFrom)
586 return io.CopyBuffer(writerOnly{w}, src, buf)
589 // Copy the first sniffLen bytes before switching to ReadFrom.
590 // This ensures we don't start writing the response before the
591 // source is available (see golang.org/issue/5660) and provides
592 // enough bytes to perform Content-Type sniffing when required.
593 if !w.cw.wroteHeader {
594 n0, err := io.CopyBuffer(writerOnly{w}, io.LimitReader(src, sniffLen), buf)
596 if err != nil || n0 < sniffLen {
601 w.w.Flush() // get rid of any previous writes
602 w.cw.flush() // make sure Header is written; flush data to rwc
604 // Now that cw has been flushed, its chunking field is guaranteed initialized.
605 if !w.cw.chunking && w.bodyAllowed() {
606 n0, err := rf.ReadFrom(src)
612 n0, err := io.CopyBuffer(writerOnly{w}, src, buf)
617 // debugServerConnections controls whether all server connections are wrapped
618 // with a verbose logging wrapper.
619 const debugServerConnections = false
621 // Create new connection from rwc.
622 func (srv *Server) newConn(rwc net.Conn) *conn {
627 if debugServerConnections {
628 c.rwc = newLoggingConn("server", c.rwc)
633 type readResult struct {
637 b byte // byte read, if n == 1
640 // connReader is the io.Reader wrapper used by *conn. It combines a
641 // selectively-activated io.LimitedReader (to bound request header
642 // read sizes) with support for selectively keeping an io.Reader.Read
643 // call blocked in a background goroutine to wait for activity and
644 // trigger a CloseNotifier channel.
645 type connReader struct {
648 mu sync.Mutex // guards following
653 aborted bool // set true before conn.rwc deadline is set to past
654 remain int64 // bytes remaining
657 func (cr *connReader) lock() {
660 cr.cond = sync.NewCond(&cr.mu)
664 func (cr *connReader) unlock() { cr.mu.Unlock() }
666 func (cr *connReader) startBackgroundRead() {
670 panic("invalid concurrent Body.Read call")
676 cr.conn.rwc.SetReadDeadline(time.Time{})
677 go cr.backgroundRead()
680 func (cr *connReader) backgroundRead() {
681 n, err := cr.conn.rwc.Read(cr.byteBuf[:])
685 // We were past the end of the previous request's body already
686 // (since we wouldn't be in a background read otherwise), so
687 // this is a pipelined HTTP request. Prior to Go 1.11 we used to
688 // send on the CloseNotify channel and cancel the context here,
689 // but the behavior was documented as only "may", and we only
690 // did that because that's how CloseNotify accidentally behaved
691 // in very early Go releases prior to context support. Once we
692 // added context support, people used a Handler's
693 // Request.Context() and passed it along. Having that context
694 // cancel on pipelined HTTP requests caused problems.
695 // Fortunately, almost nothing uses HTTP/1.x pipelining.
696 // Unfortunately, apt-get does, or sometimes does.
697 // New Go 1.11 behavior: don't fire CloseNotify or cancel
698 // contexts on pipelined requests. Shouldn't affect people, but
699 // fixes cases like Issue 23921. This does mean that a client
700 // closing their TCP connection after sending a pipelined
701 // request won't cancel the context, but we'll catch that on any
702 // write failure (in checkConnErrorWriter.Write).
703 // If the server never writes, yes, there are still contrived
704 // server & client behaviors where this fails to ever cancel the
705 // context, but that's kinda why HTTP/1.x pipelining died
708 if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
709 // Ignore this error. It's the expected error from
710 // another goroutine calling abortPendingRead.
711 } else if err != nil {
712 cr.handleReadError(err)
720 func (cr *connReader) abortPendingRead() {
727 cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
731 cr.conn.rwc.SetReadDeadline(time.Time{})
734 func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
735 func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 }
736 func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 }
738 // handleReadError is called whenever a Read from the client returns a
741 // The provided non-nil err is almost always io.EOF or a "use of
742 // closed network connection". In any case, the error is not
743 // particularly interesting, except perhaps for debugging during
744 // development. Any error means the connection is dead and we should
747 // It may be called from multiple goroutines.
748 func (cr *connReader) handleReadError(_ error) {
753 // may be called from multiple goroutines.
754 func (cr *connReader) closeNotify() {
755 res := cr.conn.curReq.Load()
756 if res != nil && !res.didCloseNotify.Swap(true) {
757 res.closeNotifyCh <- true
761 func (cr *connReader) Read(p []byte) (n int, err error) {
765 if cr.conn.hijacked() {
766 panic("invalid Body.Read call. After hijacked, the original Request must not be used")
768 panic("invalid concurrent Body.Read call")
770 if cr.hitReadLimit() {
778 if int64(len(p)) > cr.remain {
789 n, err = cr.conn.rwc.Read(p)
794 cr.handleReadError(err)
796 cr.remain -= int64(n)
804 bufioReaderPool sync.Pool
805 bufioWriter2kPool sync.Pool
806 bufioWriter4kPool sync.Pool
809 var copyBufPool = sync.Pool{
811 b := make([]byte, 32*1024)
816 func bufioWriterPool(size int) *sync.Pool {
819 return &bufioWriter2kPool
821 return &bufioWriter4kPool
826 func newBufioReader(r io.Reader) *bufio.Reader {
827 if v := bufioReaderPool.Get(); v != nil {
828 br := v.(*bufio.Reader)
832 // Note: if this reader size is ever changed, update
833 // TestHandlerBodyClose's assumptions.
834 return bufio.NewReader(r)
837 func putBufioReader(br *bufio.Reader) {
839 bufioReaderPool.Put(br)
842 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
843 pool := bufioWriterPool(size)
845 if v := pool.Get(); v != nil {
846 bw := v.(*bufio.Writer)
851 return bufio.NewWriterSize(w, size)
854 func putBufioWriter(bw *bufio.Writer) {
856 if pool := bufioWriterPool(bw.Available()); pool != nil {
861 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
862 // in an HTTP request.
863 // This can be overridden by setting Server.MaxHeaderBytes.
864 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
866 func (srv *Server) maxHeaderBytes() int {
867 if srv.MaxHeaderBytes > 0 {
868 return srv.MaxHeaderBytes
870 return DefaultMaxHeaderBytes
873 func (srv *Server) initialReadLimitSize() int64 {
874 return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
877 // tlsHandshakeTimeout returns the time limit permitted for the TLS
878 // handshake, or zero for unlimited.
880 // It returns the minimum of any positive ReadHeaderTimeout,
881 // ReadTimeout, or WriteTimeout.
882 func (srv *Server) tlsHandshakeTimeout() time.Duration {
883 var ret time.Duration
884 for _, v := range [...]time.Duration{
885 srv.ReadHeaderTimeout,
892 if ret == 0 || v < ret {
899 // wrapper around io.ReadCloser which on first read, sends an
900 // HTTP/1.1 100 Continue header
901 type expectContinueReader struct {
903 readCloser io.ReadCloser
908 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
909 if ecr.closed.Load() {
910 return 0, ErrBodyReadAfterClose
913 if !w.wroteContinue && w.canWriteContinue.Load() && !w.conn.hijacked() {
914 w.wroteContinue = true
915 w.writeContinueMu.Lock()
916 if w.canWriteContinue.Load() {
917 w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
919 w.canWriteContinue.Store(false)
921 w.writeContinueMu.Unlock()
923 n, err = ecr.readCloser.Read(p)
925 ecr.sawEOF.Store(true)
930 func (ecr *expectContinueReader) Close() error {
931 ecr.closed.Store(true)
932 return ecr.readCloser.Close()
935 // TimeFormat is the time format to use when generating times in HTTP
936 // headers. It is like time.RFC1123 but hard-codes GMT as the time
937 // zone. The time being formatted must be in UTC for Format to
938 // generate the correct format.
940 // For parsing this time format, see ParseTime.
941 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
943 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
944 func appendTime(b []byte, t time.Time) []byte {
945 const days = "SunMonTueWedThuFriSat"
946 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
949 yy, mm, dd := t.Date()
950 hh, mn, ss := t.Clock()
951 day := days[3*t.Weekday():]
952 mon := months[3*(mm-1):]
955 day[0], day[1], day[2], ',', ' ',
956 byte('0'+dd/10), byte('0'+dd%10), ' ',
957 mon[0], mon[1], mon[2], ' ',
958 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
959 byte('0'+hh/10), byte('0'+hh%10), ':',
960 byte('0'+mn/10), byte('0'+mn%10), ':',
961 byte('0'+ss/10), byte('0'+ss%10), ' ',
965 var errTooLarge = errors.New("http: request too large")
967 // Read next request from connection.
968 func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
970 return nil, ErrHijacked
974 wholeReqDeadline time.Time // or zero if none
975 hdrDeadline time.Time // or zero if none
978 if d := c.server.readHeaderTimeout(); d > 0 {
979 hdrDeadline = t0.Add(d)
981 if d := c.server.ReadTimeout; d > 0 {
982 wholeReqDeadline = t0.Add(d)
984 c.rwc.SetReadDeadline(hdrDeadline)
985 if d := c.server.WriteTimeout; d > 0 {
987 c.rwc.SetWriteDeadline(time.Now().Add(d))
991 c.r.setReadLimit(c.server.initialReadLimitSize())
992 if c.lastMethod == "POST" {
993 // RFC 7230 section 3 tolerance for old buggy clients.
994 peek, _ := c.bufr.Peek(4) // ReadRequest will get err below
995 c.bufr.Discard(numLeadingCRorLF(peek))
997 req, err := readRequest(c.bufr)
999 if c.r.hitReadLimit() {
1000 return nil, errTooLarge
1005 if !http1ServerSupportsRequest(req) {
1006 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"}
1009 c.lastMethod = req.Method
1010 c.r.setInfiniteReadLimit()
1012 hosts, haveHost := req.Header["Host"]
1013 isH2Upgrade := req.isH2Upgrade()
1014 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
1015 return nil, badRequestError("missing required Host header")
1017 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
1018 return nil, badRequestError("malformed Host header")
1020 for k, vv := range req.Header {
1021 if !httpguts.ValidHeaderFieldName(k) {
1022 return nil, badRequestError("invalid header name")
1024 for _, v := range vv {
1025 if !httpguts.ValidHeaderFieldValue(v) {
1026 return nil, badRequestError("invalid header value")
1030 delete(req.Header, "Host")
1032 ctx, cancelCtx := context.WithCancel(ctx)
1034 req.RemoteAddr = c.remoteAddr
1035 req.TLS = c.tlsState
1036 if body, ok := req.Body.(*body); ok {
1037 body.doEarlyClose = true
1040 // Adjust the read deadline if necessary.
1041 if !hdrDeadline.Equal(wholeReqDeadline) {
1042 c.rwc.SetReadDeadline(wholeReqDeadline)
1047 cancelCtx: cancelCtx,
1050 handlerHeader: make(Header),
1052 closeNotifyCh: make(chan bool, 1),
1054 // We populate these ahead of time so we're not
1055 // reading from req.Header after their Handler starts
1056 // and maybe mutates it (Issue 14940)
1057 wants10KeepAlive: req.wantsHttp10KeepAlive(),
1058 wantsClose: req.wantsClose(),
1061 w.closeAfterReply = true
1064 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
1068 // http1ServerSupportsRequest reports whether Go's HTTP/1.x server
1069 // supports the given request.
1070 func http1ServerSupportsRequest(req *Request) bool {
1071 if req.ProtoMajor == 1 {
1074 // Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
1075 // wire up their own HTTP/2 upgrades.
1076 if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
1077 req.Method == "PRI" && req.RequestURI == "*" {
1080 // Reject HTTP/0.x, and all other HTTP/2+ requests (which
1081 // aren't encoded in ASCII anyway).
1085 func (w *response) Header() Header {
1086 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
1087 // Accessing the header between logically writing it
1088 // and physically writing it means we need to allocate
1089 // a clone to snapshot the logically written state.
1090 w.cw.header = w.handlerHeader.Clone()
1092 w.calledHeader = true
1093 return w.handlerHeader
1096 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
1097 // consumed by a handler that the server will read from the client
1098 // in order to keep a connection alive. If there are more bytes than
1099 // this then the server to be paranoid instead sends a "Connection:
1102 // This number is approximately what a typical machine's TCP buffer
1103 // size is anyway. (if we have the bytes on the machine, we might as
1105 const maxPostHandlerReadBytes = 256 << 10
1107 func checkWriteHeaderCode(code int) {
1108 // Issue 22880: require valid WriteHeader status codes.
1109 // For now we only enforce that it's three digits.
1110 // In the future we might block things over 599 (600 and above aren't defined
1111 // at https://httpwg.org/specs/rfc7231.html#status.codes).
1112 // But for now any three digits.
1114 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
1115 // no equivalent bogus thing we can realistically send in HTTP/2,
1116 // so we'll consistently panic instead and help people find their bugs
1117 // early. (We can't return an error from WriteHeader even if we wanted to.)
1118 if code < 100 || code > 999 {
1119 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
1123 // relevantCaller searches the call stack for the first function outside of net/http.
1124 // The purpose of this function is to provide more helpful error messages.
1125 func relevantCaller() runtime.Frame {
1126 pc := make([]uintptr, 16)
1127 n := runtime.Callers(1, pc)
1128 frames := runtime.CallersFrames(pc[:n])
1129 var frame runtime.Frame
1131 frame, more := frames.Next()
1132 if !strings.HasPrefix(frame.Function, "net/http.") {
1142 func (w *response) WriteHeader(code int) {
1143 if w.conn.hijacked() {
1144 caller := relevantCaller()
1145 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1149 caller := relevantCaller()
1150 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1153 checkWriteHeaderCode(code)
1155 // Handle informational headers.
1157 // We shouldn't send any further headers after 101 Switching Protocols,
1158 // so it takes the non-informational path.
1159 if code >= 100 && code <= 199 && code != StatusSwitchingProtocols {
1160 // Prevent a potential race with an automatically-sent 100 Continue triggered by Request.Body.Read()
1161 if code == 100 && w.canWriteContinue.Load() {
1162 w.writeContinueMu.Lock()
1163 w.canWriteContinue.Store(false)
1164 w.writeContinueMu.Unlock()
1167 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1169 // Per RFC 8297 we must not clear the current header map
1170 w.handlerHeader.WriteSubset(w.conn.bufw, excludedHeadersNoBody)
1171 w.conn.bufw.Write(crlf)
1177 w.wroteHeader = true
1180 if w.calledHeader && w.cw.header == nil {
1181 w.cw.header = w.handlerHeader.Clone()
1184 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
1185 v, err := strconv.ParseInt(cl, 10, 64)
1186 if err == nil && v >= 0 {
1189 w.conn.server.logf("http: invalid Content-Length of %q", cl)
1190 w.handlerHeader.Del("Content-Length")
1195 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
1196 // This type is used to avoid extra allocations from cloning and/or populating
1197 // the response Header map and all its 1-element slices.
1198 type extraHeader struct {
1201 transferEncoding string
1202 date []byte // written if not nil
1203 contentLength []byte // written if not nil
1206 // Sorted the same as extraHeader.Write's loop.
1207 var extraHeaderKeys = [][]byte{
1208 []byte("Content-Type"),
1209 []byte("Connection"),
1210 []byte("Transfer-Encoding"),
1214 headerContentLength = []byte("Content-Length: ")
1215 headerDate = []byte("Date: ")
1218 // Write writes the headers described in h to w.
1220 // This method has a value receiver, despite the somewhat large size
1221 // of h, because it prevents an allocation. The escape analysis isn't
1222 // smart enough to realize this function doesn't mutate h.
1223 func (h extraHeader) Write(w *bufio.Writer) {
1229 if h.contentLength != nil {
1230 w.Write(headerContentLength)
1231 w.Write(h.contentLength)
1234 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
1236 w.Write(extraHeaderKeys[i])
1244 // writeHeader finalizes the header sent to the client and writes it
1245 // to cw.res.conn.bufw.
1247 // p is not written by writeHeader, but is the first chunk of the body
1248 // that will be written. It is sniffed for a Content-Type if none is
1249 // set explicitly. It's also used to set the Content-Length, if the
1250 // total body size was small and the handler has already finished
1252 func (cw *chunkWriter) writeHeader(p []byte) {
1256 cw.wroteHeader = true
1259 keepAlivesEnabled := w.conn.server.doKeepAlives()
1260 isHEAD := w.req.Method == "HEAD"
1262 // header is written out to w.conn.buf below. Depending on the
1263 // state of the handler, we either own the map or not. If we
1264 // don't own it, the exclude map is created lazily for
1265 // WriteSubset to remove headers. The setHeader struct holds
1266 // headers we need to add.
1268 owned := header != nil
1270 header = w.handlerHeader
1272 var excludeHeader map[string]bool
1273 delHeader := func(key string) {
1278 if _, ok := header[key]; !ok {
1281 if excludeHeader == nil {
1282 excludeHeader = make(map[string]bool)
1284 excludeHeader[key] = true
1286 var setHeader extraHeader
1288 // Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
1290 for k := range cw.header {
1291 if strings.HasPrefix(k, TrailerPrefix) {
1292 if excludeHeader == nil {
1293 excludeHeader = make(map[string]bool)
1295 excludeHeader[k] = true
1299 for _, v := range cw.header["Trailer"] {
1301 foreachHeaderElement(v, cw.res.declareTrailer)
1304 te := header.get("Transfer-Encoding")
1307 // If the handler is done but never sent a Content-Length
1308 // response header and this is our first (and last) write, set
1309 // it, even to zero. This helps HTTP/1.0 clients keep their
1310 // "keep-alive" connections alive.
1311 // Exceptions: 304/204/1xx responses never get Content-Length, and if
1312 // it was a HEAD request, we don't know the difference between
1313 // 0 actual bytes and 0 bytes because the handler noticed it
1314 // was a HEAD request and chose not to write anything. So for
1315 // HEAD, the handler should either write the Content-Length or
1316 // write non-zero bytes. If it's actually 0 bytes and the
1317 // handler never looked at the Request.Method, we just don't
1318 // send a Content-Length header.
1319 // Further, we don't send an automatic Content-Length if they
1320 // set a Transfer-Encoding, because they're generally incompatible.
1321 if w.handlerDone.Load() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && !header.has("Content-Length") && (!isHEAD || len(p) > 0) {
1322 w.contentLength = int64(len(p))
1323 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
1326 // If this was an HTTP/1.0 request with keep-alive and we sent a
1327 // Content-Length back, we can make this a keep-alive response ...
1328 if w.wants10KeepAlive && keepAlivesEnabled {
1329 sentLength := header.get("Content-Length") != ""
1330 if sentLength && header.get("Connection") == "keep-alive" {
1331 w.closeAfterReply = false
1335 // Check for an explicit (and valid) Content-Length header.
1336 hasCL := w.contentLength != -1
1338 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
1339 _, connectionHeaderSet := header["Connection"]
1340 if !connectionHeaderSet {
1341 setHeader.connection = "keep-alive"
1343 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
1344 w.closeAfterReply = true
1347 if header.get("Connection") == "close" || !keepAlivesEnabled {
1348 w.closeAfterReply = true
1351 // If the client wanted a 100-continue but we never sent it to
1352 // them (or, more strictly: we never finished reading their
1353 // request body), don't reuse this connection because it's now
1354 // in an unknown state: we might be sending this response at
1355 // the same time the client is now sending its request body
1356 // after a timeout. (Some HTTP clients send Expect:
1357 // 100-continue but knowing that some servers don't support
1358 // it, the clients set a timer and send the body later anyway)
1359 // If we haven't seen EOF, we can't skip over the unread body
1360 // because we don't know if the next bytes on the wire will be
1361 // the body-following-the-timer or the subsequent request.
1363 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
1364 w.closeAfterReply = true
1367 // We do this by default because there are a number of clients that
1368 // send a full request before starting to read the response, and they
1369 // can deadlock if we start writing the response with unconsumed body
1370 // remaining. See Issue 15527 for some history.
1372 // If full duplex mode has been enabled with ResponseController.EnableFullDuplex,
1373 // then leave the request body alone.
1374 if w.req.ContentLength != 0 && !w.closeAfterReply && !w.fullDuplex {
1375 var discard, tooBig bool
1377 switch bdy := w.req.Body.(type) {
1378 case *expectContinueReader:
1379 if bdy.resp.wroteContinue {
1387 // Body was closed in handler with non-EOF error.
1388 w.closeAfterReply = true
1390 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1401 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1404 // There must be even more data left over.
1406 case ErrBodyReadAfterClose:
1407 // Body was already consumed and closed.
1409 // The remaining body was just consumed, close it.
1410 err = w.reqBody.Close()
1412 w.closeAfterReply = true
1415 // Some other kind of error occurred, like a read timeout, or
1416 // corrupt chunked encoding. In any case, whatever remains
1417 // on the wire must not be parsed as another HTTP request.
1418 w.closeAfterReply = true
1424 delHeader("Connection")
1425 setHeader.connection = "close"
1430 if bodyAllowedForStatus(code) {
1431 // If no content type, apply sniffing algorithm to body.
1432 _, haveType := header["Content-Type"]
1434 // If the Content-Encoding was set and is non-blank,
1435 // we shouldn't sniff the body. See Issue 31753.
1436 ce := header.Get("Content-Encoding")
1437 hasCE := len(ce) > 0
1438 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1439 setHeader.contentType = DetectContentType(p)
1442 for _, k := range suppressedHeaders(code) {
1447 if !header.has("Date") {
1448 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1451 if hasCL && hasTE && te != "identity" {
1452 // TODO: return an error if WriteHeader gets a return parameter
1453 // For now just ignore the Content-Length.
1454 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1455 te, w.contentLength)
1456 delHeader("Content-Length")
1460 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1461 // Response has no body.
1462 delHeader("Transfer-Encoding")
1464 // Content-Length has been provided, so no chunking is to be done.
1465 delHeader("Transfer-Encoding")
1466 } else if w.req.ProtoAtLeast(1, 1) {
1467 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
1468 // content-length has been provided. The connection must be closed after the
1469 // reply is written, and no chunking is to be done. This is the setup
1470 // recommended in the Server-Sent Events candidate recommendation 11,
1472 if hasTE && te == "identity" {
1474 w.closeAfterReply = true
1475 delHeader("Transfer-Encoding")
1477 // HTTP/1.1 or greater: use chunked transfer encoding
1478 // to avoid closing the connection at EOF.
1480 setHeader.transferEncoding = "chunked"
1481 if hasTE && te == "chunked" {
1482 // We will send the chunked Transfer-Encoding header later.
1483 delHeader("Transfer-Encoding")
1487 // HTTP version < 1.1: cannot do chunked transfer
1488 // encoding and we don't know the Content-Length so
1489 // signal EOF by closing connection.
1490 w.closeAfterReply = true
1491 delHeader("Transfer-Encoding") // in case already set
1494 // Cannot use Content-Length with non-identity Transfer-Encoding.
1496 delHeader("Content-Length")
1498 if !w.req.ProtoAtLeast(1, 0) {
1502 // Only override the Connection header if it is not a successful
1503 // protocol switch response and if KeepAlives are not enabled.
1504 // See https://golang.org/issue/36381.
1505 delConnectionHeader := w.closeAfterReply &&
1506 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1507 !isProtocolSwitchResponse(w.status, header)
1508 if delConnectionHeader {
1509 delHeader("Connection")
1510 if w.req.ProtoAtLeast(1, 1) {
1511 setHeader.connection = "close"
1515 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1516 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1517 setHeader.Write(w.conn.bufw)
1518 w.conn.bufw.Write(crlf)
1521 // foreachHeaderElement splits v according to the "#rule" construction
1522 // in RFC 7230 section 7 and calls fn for each non-empty element.
1523 func foreachHeaderElement(v string, fn func(string)) {
1524 v = textproto.TrimString(v)
1528 if !strings.Contains(v, ",") {
1532 for _, f := range strings.Split(v, ",") {
1533 if f = textproto.TrimString(f); f != "" {
1539 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
1540 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
1541 // code is the response status code.
1542 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
1543 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1545 bw.WriteString("HTTP/1.1 ")
1547 bw.WriteString("HTTP/1.0 ")
1549 if text := StatusText(code); text != "" {
1550 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1552 bw.WriteString(text)
1553 bw.WriteString("\r\n")
1555 // don't worry about performance
1556 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1560 // bodyAllowed reports whether a Write is allowed for this response type.
1561 // It's illegal to call this before the header has been flushed.
1562 func (w *response) bodyAllowed() bool {
1566 return bodyAllowedForStatus(w.status)
1569 // The Life Of A Write is like this:
1571 // Handler starts. No header has been sent. The handler can either
1572 // write a header, or just start writing. Writing before sending a header
1573 // sends an implicitly empty 200 OK header.
1575 // If the handler didn't declare a Content-Length up front, we either
1576 // go into chunking mode or, if the handler finishes running before
1577 // the chunking buffer size, we compute a Content-Length and send that
1578 // in the header instead.
1580 // Likewise, if the handler didn't set a Content-Type, we sniff that
1581 // from the initial chunk of output.
1583 // The Writers are wired together like:
1585 // 1. *response (the ResponseWriter) ->
1586 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes ->
1587 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
1588 // and which writes the chunk headers, if needed ->
1589 // 4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to ->
1590 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
1591 // and populates c.werr with it if so, but otherwise writes to ->
1592 // 6. the rwc, the net.Conn.
1594 // TODO(bradfitz): short-circuit some of the buffering when the
1595 // initial header contains both a Content-Type and Content-Length.
1596 // Also short-circuit in (1) when the header's been sent and not in
1597 // chunking mode, writing directly to (4) instead, if (2) has no
1598 // buffered data. More generally, we could short-circuit from (1) to
1599 // (3) even in chunking mode if the write size from (1) is over some
1600 // threshold and nothing is in (2). The answer might be mostly making
1601 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
1602 // with this instead.
1603 func (w *response) Write(data []byte) (n int, err error) {
1604 return w.write(len(data), data, "")
1607 func (w *response) WriteString(data string) (n int, err error) {
1608 return w.write(len(data), nil, data)
1611 // either dataB or dataS is non-zero.
1612 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1613 if w.conn.hijacked() {
1615 caller := relevantCaller()
1616 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1618 return 0, ErrHijacked
1621 if w.canWriteContinue.Load() {
1622 // Body reader wants to write 100 Continue but hasn't yet.
1623 // Tell it not to. The store must be done while holding the lock
1624 // because the lock makes sure that there is not an active write
1625 // this very moment.
1626 w.writeContinueMu.Lock()
1627 w.canWriteContinue.Store(false)
1628 w.writeContinueMu.Unlock()
1632 w.WriteHeader(StatusOK)
1637 if !w.bodyAllowed() {
1638 return 0, ErrBodyNotAllowed
1641 w.written += int64(lenData) // ignoring errors, for errorKludge
1642 if w.contentLength != -1 && w.written > w.contentLength {
1643 return 0, ErrContentLength
1646 return w.w.Write(dataB)
1648 return w.w.WriteString(dataS)
1652 func (w *response) finishRequest() {
1653 w.handlerDone.Store(true)
1656 w.WriteHeader(StatusOK)
1664 w.conn.r.abortPendingRead()
1666 // Close the body (regardless of w.closeAfterReply) so we can
1667 // re-use its bufio.Reader later safely.
1670 if w.req.MultipartForm != nil {
1671 w.req.MultipartForm.RemoveAll()
1675 // shouldReuseConnection reports whether the underlying TCP connection can be reused.
1676 // It must only be called after the handler is done executing.
1677 func (w *response) shouldReuseConnection() bool {
1678 if w.closeAfterReply {
1679 // The request or something set while executing the
1680 // handler indicated we shouldn't reuse this
1685 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1686 // Did not write enough. Avoid getting out of sync.
1690 // There was some error writing to the underlying connection
1691 // during the request, so don't re-use this conn.
1692 if w.conn.werr != nil {
1696 if w.closedRequestBodyEarly() {
1703 func (w *response) closedRequestBodyEarly() bool {
1704 body, ok := w.req.Body.(*body)
1705 return ok && body.didEarlyClose()
1708 func (w *response) Flush() {
1712 func (w *response) FlushError() error {
1714 w.WriteHeader(StatusOK)
1724 func (c *conn) finalFlush() {
1726 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1727 // reader for a future connection.
1728 putBufioReader(c.bufr)
1734 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1735 // writer for a future connection.
1736 putBufioWriter(c.bufw)
1741 // Close the connection.
1742 func (c *conn) close() {
1747 // rstAvoidanceDelay is the amount of time we sleep after closing the
1748 // write side of a TCP connection before closing the entire socket.
1749 // By sleeping, we increase the chances that the client sees our FIN
1750 // and processes its final data before they process the subsequent RST
1751 // from closing a connection with known unread data.
1752 // This RST seems to occur mostly on BSD systems. (And Windows?)
1753 // This timeout is somewhat arbitrary (~latency around the planet),
1754 // and may be modified by tests.
1756 // TODO(bcmills): This should arguably be a server configuration parameter,
1757 // not a hard-coded value.
1758 var rstAvoidanceDelay = 500 * time.Millisecond
1760 type closeWriter interface {
1764 var _ closeWriter = (*net.TCPConn)(nil)
1766 // closeWriteAndWait flushes any outstanding data and sends a FIN packet (if
1767 // client is connected via TCP), signaling that we're done. We then
1768 // pause for a bit, hoping the client processes it before any
1771 // See https://golang.org/issue/3595
1772 func (c *conn) closeWriteAndWait() {
1774 if tcp, ok := c.rwc.(closeWriter); ok {
1778 // When we return from closeWriteAndWait, the caller will fully close the
1779 // connection. If client is still writing to the connection, this will cause
1780 // the write to fail with ECONNRESET or similar. Unfortunately, many TCP
1781 // implementations will also drop unread packets from the client's read buffer
1782 // when a write fails, causing our final response to be truncated away too.
1784 // As a result, https://www.rfc-editor.org/rfc/rfc7230#section-6.6 recommends
1785 // that “[t]he server … continues to read from the connection until it
1786 // receives a corresponding close by the client, or until the server is
1787 // reasonably certain that its own TCP stack has received the client's
1788 // acknowledgement of the packet(s) containing the server's last response.”
1790 // Unfortunately, we have no straightforward way to be “reasonably certain”
1791 // that we have received the client's ACK, and at any rate we don't want to
1792 // allow a misbehaving client to soak up server connections indefinitely by
1793 // withholding an ACK, nor do we want to go through the complexity or overhead
1794 // of using low-level APIs to figure out when a TCP round-trip has completed.
1796 // Instead, we declare that we are “reasonably certain” that we received the
1797 // ACK if maxRSTAvoidanceDelay has elapsed.
1798 time.Sleep(rstAvoidanceDelay)
1801 // validNextProto reports whether the proto is a valid ALPN protocol name.
1802 // Everything is valid except the empty string and built-in protocol types,
1803 // so that those can't be overridden with alternate implementations.
1804 func validNextProto(proto string) bool {
1806 case "", "http/1.1", "http/1.0":
1817 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1821 srv.trackConn(c, true)
1822 case StateHijacked, StateClosed:
1823 srv.trackConn(c, false)
1825 if state > 0xff || state < 0 {
1826 panic("internal error")
1828 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1829 c.curState.Store(packedState)
1833 if hook := srv.ConnState; hook != nil {
1838 func (c *conn) getState() (state ConnState, unixSec int64) {
1839 packedState := c.curState.Load()
1840 return ConnState(packedState & 0xff), int64(packedState >> 8)
1843 // badRequestError is a literal string (used by in the server in HTML,
1844 // unescaped) to tell the user why their request was bad. It should
1845 // be plain text without user info or other embedded errors.
1846 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1848 // statusError is an error used to respond to a request with an HTTP status.
1849 // The text should be plain text without user info or other embedded errors.
1850 type statusError struct {
1855 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1857 // ErrAbortHandler is a sentinel panic value to abort a handler.
1858 // While any panic from ServeHTTP aborts the response to the client,
1859 // panicking with ErrAbortHandler also suppresses logging of a stack
1860 // trace to the server's error log.
1861 var ErrAbortHandler = errors.New("net/http: abort Handler")
1863 // isCommonNetReadError reports whether err is a common error
1864 // encountered during reading a request off the network when the
1865 // client has gone away or had its read fail somehow. This is used to
1866 // determine which logs are interesting enough to log about.
1867 func isCommonNetReadError(err error) bool {
1871 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1874 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1880 // Serve a new connection.
1881 func (c *conn) serve(ctx context.Context) {
1882 if ra := c.rwc.RemoteAddr(); ra != nil {
1883 c.remoteAddr = ra.String()
1885 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1886 var inFlightResponse *response
1888 if err := recover(); err != nil && err != ErrAbortHandler {
1889 const size = 64 << 10
1890 buf := make([]byte, size)
1891 buf = buf[:runtime.Stack(buf, false)]
1892 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1894 if inFlightResponse != nil {
1895 inFlightResponse.cancelCtx()
1898 if inFlightResponse != nil {
1899 inFlightResponse.conn.r.abortPendingRead()
1900 inFlightResponse.reqBody.Close()
1903 c.setState(c.rwc, StateClosed, runHooks)
1907 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1908 tlsTO := c.server.tlsHandshakeTimeout()
1910 dl := time.Now().Add(tlsTO)
1911 c.rwc.SetReadDeadline(dl)
1912 c.rwc.SetWriteDeadline(dl)
1914 if err := tlsConn.HandshakeContext(ctx); err != nil {
1915 // If the handshake failed due to the client not speaking
1916 // TLS, assume they're speaking plaintext HTTP and write a
1917 // 400 response on the TLS conn's underlying net.Conn.
1918 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1919 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1923 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1926 // Restore Conn-level deadlines.
1928 c.rwc.SetReadDeadline(time.Time{})
1929 c.rwc.SetWriteDeadline(time.Time{})
1931 c.tlsState = new(tls.ConnectionState)
1932 *c.tlsState = tlsConn.ConnectionState()
1933 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1934 if fn := c.server.TLSNextProto[proto]; fn != nil {
1935 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1936 // Mark freshly created HTTP/2 as active and prevent any server state hooks
1937 // from being run on these connections. This prevents closeIdleConns from
1938 // closing such connections. See issue https://golang.org/issue/39776.
1939 c.setState(c.rwc, StateActive, skipHooks)
1940 fn(c.server, tlsConn, h)
1946 // HTTP/1.x from here on.
1948 ctx, cancelCtx := context.WithCancel(ctx)
1949 c.cancelCtx = cancelCtx
1952 c.r = &connReader{conn: c}
1953 c.bufr = newBufioReader(c.r)
1954 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1957 w, err := c.readRequest(ctx)
1958 if c.r.remain != c.server.initialReadLimitSize() {
1959 // If we read any bytes off the wire, we're active.
1960 c.setState(c.rwc, StateActive, runHooks)
1963 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1966 case err == errTooLarge:
1967 // Their HTTP client may or may not be
1968 // able to read this if we're
1969 // responding to them and hanging up
1970 // while they're still writing their
1971 // request. Undefined behavior.
1972 const publicErr = "431 Request Header Fields Too Large"
1973 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1974 c.closeWriteAndWait()
1977 case isUnsupportedTEError(err):
1978 // Respond as per RFC 7230 Section 3.3.1 which says,
1979 // A server that receives a request message with a
1980 // transfer coding it does not understand SHOULD
1981 // respond with 501 (Unimplemented).
1982 code := StatusNotImplemented
1984 // We purposefully aren't echoing back the transfer-encoding's value,
1985 // so as to mitigate the risk of cross side scripting by an attacker.
1986 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1989 case isCommonNetReadError(err):
1990 return // don't reply
1993 if v, ok := err.(statusError); ok {
1994 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)
1997 const publicErr = "400 Bad Request"
1998 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
2003 // Expect 100 Continue support
2005 if req.expectsContinue() {
2006 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
2007 // Wrap the Body reader with one that replies on the connection
2008 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
2009 w.canWriteContinue.Store(true)
2011 } else if req.Header.get("Expect") != "" {
2012 w.sendExpectationFailed()
2018 if requestBodyRemains(req.Body) {
2019 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
2021 w.conn.r.startBackgroundRead()
2024 // HTTP cannot have multiple simultaneous active requests.[*]
2025 // Until the server replies to this request, it can't read another,
2026 // so we might as well run the handler in this goroutine.
2027 // [*] Not strictly true: HTTP pipelining. We could let them all process
2028 // in parallel even if their responses need to be serialized.
2029 // But we're not going to implement HTTP pipelining because it
2030 // was never deployed in the wild and the answer is HTTP/2.
2031 inFlightResponse = w
2032 serverHandler{c.server}.ServeHTTP(w, w.req)
2033 inFlightResponse = nil
2039 c.rwc.SetWriteDeadline(time.Time{})
2040 if !w.shouldReuseConnection() {
2041 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
2042 c.closeWriteAndWait()
2046 c.setState(c.rwc, StateIdle, runHooks)
2049 if !w.conn.server.doKeepAlives() {
2050 // We're in shutdown mode. We might've replied
2051 // to the user without "Connection: close" and
2052 // they might think they can send another
2053 // request, but such is life with HTTP/1.1.
2057 if d := c.server.idleTimeout(); d != 0 {
2058 c.rwc.SetReadDeadline(time.Now().Add(d))
2060 c.rwc.SetReadDeadline(time.Time{})
2063 // Wait for the connection to become readable again before trying to
2064 // read the next request. This prevents a ReadHeaderTimeout or
2065 // ReadTimeout from starting until the first bytes of the next request
2066 // have been received.
2067 if _, err := c.bufr.Peek(4); err != nil {
2071 c.rwc.SetReadDeadline(time.Time{})
2075 func (w *response) sendExpectationFailed() {
2076 // TODO(bradfitz): let ServeHTTP handlers handle
2077 // requests with non-standard expectation[s]? Seems
2078 // theoretical at best, and doesn't fit into the
2079 // current ServeHTTP model anyway. We'd need to
2080 // make the ResponseWriter an optional
2081 // "ExpectReplier" interface or something.
2083 // For now we'll just obey RFC 7231 5.1.1 which says
2084 // "A server that receives an Expect field-value other
2085 // than 100-continue MAY respond with a 417 (Expectation
2086 // Failed) status code to indicate that the unexpected
2087 // expectation cannot be met."
2088 w.Header().Set("Connection", "close")
2089 w.WriteHeader(StatusExpectationFailed)
2093 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
2095 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
2096 if w.handlerDone.Load() {
2097 panic("net/http: Hijack called after ServeHTTP finished")
2107 // Release the bufioWriter that writes to the chunk writer, it is not
2108 // used after a connection has been hijacked.
2109 rwc, buf, err = c.hijackLocked()
2114 return rwc, buf, err
2117 func (w *response) CloseNotify() <-chan bool {
2118 if w.handlerDone.Load() {
2119 panic("net/http: CloseNotify called after ServeHTTP finished")
2121 return w.closeNotifyCh
2124 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2125 switch v := rc.(type) {
2126 case *expectContinueReader:
2127 registerOnHitEOF(v.readCloser, fn)
2129 v.registerOnHitEOF(fn)
2131 panic("unexpected type " + fmt.Sprintf("%T", rc))
2135 // requestBodyRemains reports whether future calls to Read
2136 // on rc might yield more data.
2137 func requestBodyRemains(rc io.ReadCloser) bool {
2141 switch v := rc.(type) {
2142 case *expectContinueReader:
2143 return requestBodyRemains(v.readCloser)
2145 return v.bodyRemains()
2147 panic("unexpected type " + fmt.Sprintf("%T", rc))
2151 // The HandlerFunc type is an adapter to allow the use of
2152 // ordinary functions as HTTP handlers. If f is a function
2153 // with the appropriate signature, HandlerFunc(f) is a
2154 // Handler that calls f.
2155 type HandlerFunc func(ResponseWriter, *Request)
2157 // ServeHTTP calls f(w, r).
2158 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2164 // Error replies to the request with the specified error message and HTTP code.
2165 // It does not otherwise end the request; the caller should ensure no further
2166 // writes are done to w.
2167 // The error message should be plain text.
2168 func Error(w ResponseWriter, error string, code int) {
2169 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2170 w.Header().Set("X-Content-Type-Options", "nosniff")
2172 fmt.Fprintln(w, error)
2175 // NotFound replies to the request with an HTTP 404 not found error.
2176 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2178 // NotFoundHandler returns a simple request handler
2179 // that replies to each request with a “404 page not found” reply.
2180 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2182 // StripPrefix returns a handler that serves HTTP requests by removing the
2183 // given prefix from the request URL's Path (and RawPath if set) and invoking
2184 // the handler h. StripPrefix handles a request for a path that doesn't begin
2185 // with prefix by replying with an HTTP 404 not found error. The prefix must
2186 // match exactly: if the prefix in the request contains escaped characters
2187 // the reply is also an HTTP 404 not found error.
2188 func StripPrefix(prefix string, h Handler) Handler {
2192 return HandlerFunc(func(w ResponseWriter, r *Request) {
2193 p := strings.TrimPrefix(r.URL.Path, prefix)
2194 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2195 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2198 r2.URL = new(url.URL)
2209 // Redirect replies to the request with a redirect to url,
2210 // which may be a path relative to the request path.
2212 // The provided code should be in the 3xx range and is usually
2213 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2215 // If the Content-Type header has not been set, Redirect sets it
2216 // to "text/html; charset=utf-8" and writes a small HTML body.
2217 // Setting the Content-Type header to any value, including nil,
2218 // disables that behavior.
2219 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2220 if u, err := urlpkg.Parse(url); err == nil {
2221 // If url was relative, make its path absolute by
2222 // combining with request path.
2223 // The client would probably do this for us,
2224 // but doing it ourselves is more reliable.
2225 // See RFC 7231, section 7.1.2
2226 if u.Scheme == "" && u.Host == "" {
2227 oldpath := r.URL.Path
2228 if oldpath == "" { // should not happen, but avoid a crash if it does
2232 // no leading http://server
2233 if url == "" || url[0] != '/' {
2234 // make relative path absolute
2235 olddir, _ := path.Split(oldpath)
2240 if i := strings.Index(url, "?"); i != -1 {
2241 url, query = url[:i], url[i:]
2244 // clean up but preserve trailing slash
2245 trailing := strings.HasSuffix(url, "/")
2246 url = path.Clean(url)
2247 if trailing && !strings.HasSuffix(url, "/") {
2256 // RFC 7231 notes that a short HTML body is usually included in
2257 // the response because older user agents may not understand 301/307.
2258 // Do it only if the request didn't already have a Content-Type header.
2259 _, hadCT := h["Content-Type"]
2261 h.Set("Location", hexEscapeNonASCII(url))
2262 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2263 h.Set("Content-Type", "text/html; charset=utf-8")
2267 // Shouldn't send the body for POST or HEAD; that leaves GET.
2268 if !hadCT && r.Method == "GET" {
2269 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
2270 fmt.Fprintln(w, body)
2274 var htmlReplacer = strings.NewReplacer(
2278 // """ is shorter than """.
2280 // "'" is shorter than "'" and apos was not in HTML until HTML5.
2284 func htmlEscape(s string) string {
2285 return htmlReplacer.Replace(s)
2288 // Redirect to a fixed URL
2289 type redirectHandler struct {
2294 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2295 Redirect(w, r, rh.url, rh.code)
2298 // RedirectHandler returns a request handler that redirects
2299 // each request it receives to the given url using the given
2302 // The provided code should be in the 3xx range and is usually
2303 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2304 func RedirectHandler(url string, code int) Handler {
2305 return &redirectHandler{url, code}
2308 // TODO(jba): rewrite the following doc for enhanced patterns (proposal
2309 // https://go.dev/issue/61410).
2311 // ServeMux is an HTTP request multiplexer.
2312 // It matches the URL of each incoming request against a list of registered
2313 // patterns and calls the handler for the pattern that
2314 // most closely matches the URL.
2316 // Patterns name fixed, rooted paths, like "/favicon.ico",
2317 // or rooted subtrees, like "/images/" (note the trailing slash).
2318 // Longer patterns take precedence over shorter ones, so that
2319 // if there are handlers registered for both "/images/"
2320 // and "/images/thumbnails/", the latter handler will be
2321 // called for paths beginning with "/images/thumbnails/" and the
2322 // former will receive requests for any other paths in the
2323 // "/images/" subtree.
2325 // Note that since a pattern ending in a slash names a rooted subtree,
2326 // the pattern "/" matches all paths not matched by other registered
2327 // patterns, not just the URL with Path == "/".
2329 // If a subtree has been registered and a request is received naming the
2330 // subtree root without its trailing slash, ServeMux redirects that
2331 // request to the subtree root (adding the trailing slash). This behavior can
2332 // be overridden with a separate registration for the path without
2333 // the trailing slash. For example, registering "/images/" causes ServeMux
2334 // to redirect a request for "/images" to "/images/", unless "/images" has
2335 // been registered separately.
2337 // Patterns may optionally begin with a host name, restricting matches to
2338 // URLs on that host only. Host-specific patterns take precedence over
2339 // general patterns, so that a handler might register for the two patterns
2340 // "/codesearch" and "codesearch.google.com/" without also taking over
2341 // requests for "http://www.google.com/".
2343 // ServeMux also takes care of sanitizing the URL request path and the Host
2344 // header, stripping the port number and redirecting any request containing . or
2345 // .. elements or repeated slashes to an equivalent, cleaner URL.
2346 type ServeMux struct {
2352 // NewServeMux allocates and returns a new ServeMux.
2353 func NewServeMux() *ServeMux {
2357 // DefaultServeMux is the default ServeMux used by Serve.
2358 var DefaultServeMux = &defaultServeMux
2360 var defaultServeMux ServeMux
2362 // cleanPath returns the canonical path for p, eliminating . and .. elements.
2363 func cleanPath(p string) string {
2371 // path.Clean removes trailing slash except for root;
2372 // put the trailing slash back if necessary.
2373 if p[len(p)-1] == '/' && np != "/" {
2374 // Fast path for common case of p being the string we want:
2375 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2384 // stripHostPort returns h without any trailing ":<port>".
2385 func stripHostPort(h string) string {
2386 // If no port on host, return unchanged
2387 if !strings.Contains(h, ":") {
2390 host, _, err := net.SplitHostPort(h)
2392 return h // on error, return unchanged
2397 // Handler returns the handler to use for the given request,
2398 // consulting r.Method, r.Host, and r.URL.Path. It always returns
2399 // a non-nil handler. If the path is not in its canonical form, the
2400 // handler will be an internally-generated handler that redirects
2401 // to the canonical path. If the host contains a port, it is ignored
2402 // when matching handlers.
2404 // The path and host are used unchanged for CONNECT requests.
2406 // Handler also returns the registered pattern that matches the
2407 // request or, in the case of internally-generated redirects,
2408 // the path that will match after following the redirect.
2410 // If there is no registered handler that applies to the request,
2411 // Handler returns a “page not found” handler and an empty pattern.
2412 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2413 h, p, _, _ := mux.findHandler(r)
2417 // findHandler finds a handler for a request.
2418 // If there is a matching handler, it returns it and the pattern that matched.
2419 // Otherwise it returns a Redirect or NotFound handler with the path that would match
2420 // after the redirect.
2421 func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
2423 // TODO(jba): use escaped path. This is an independent change that is also part
2424 // of proposal https://go.dev/issue/61410.
2427 // CONNECT requests are not canonicalized.
2428 if r.Method == "CONNECT" {
2429 // If r.URL.Path is /tree and its handler is not registered,
2430 // the /tree -> /tree/ redirect applies to CONNECT requests
2431 // but the path canonicalization does not.
2432 _, _, u := mux.matchOrRedirect(r.URL.Host, r.Method, path, r.URL)
2434 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2436 // Redo the match, this time with r.Host instead of r.URL.Host.
2437 // Pass a nil URL to skip the trailing-slash redirect logic.
2438 n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
2440 // All other requests have any port stripped and path cleaned
2441 // before passing to mux.handler.
2442 host := stripHostPort(r.Host)
2443 path = cleanPath(path)
2445 // If the given path is /tree and its handler is not registered,
2446 // redirect for /tree/.
2448 n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
2450 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
2452 if path != r.URL.Path {
2453 // Redirect to cleaned path.
2456 patStr = n.pattern.String()
2458 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2459 return RedirectHandler(u.String(), StatusMovedPermanently), patStr, nil, nil
2463 // TODO(jba): support 405 (MethodNotAllowed) by checking for patterns with different methods.
2464 return NotFoundHandler(), "", nil, nil
2466 return n.handler, n.pattern.String(), n.pattern, matches
2469 // matchOrRedirect looks up a node in the tree that matches the host, method and path.
2470 // The path is known to be in canonical form, except for CONNECT methods.
2472 // If the url argument is non-nil, handler also deals with trailing-slash
2473 // redirection: when a path doesn't match exactly, the match is tried again
2474 // after appending "/" to the path. If that second match succeeds, the last
2475 // return value is the URL to redirect to.
2476 func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
2478 defer mux.mu.RUnlock()
2480 n, matches := mux.tree.match(host, method, path)
2481 // If we have an exact match, or we were asked not to try trailing-slash redirection,
2483 if !exactMatch(n, path) && u != nil {
2484 // If there is an exact match with a trailing slash, then redirect.
2486 n2, _ := mux.tree.match(host, method, path)
2487 if exactMatch(n2, path) {
2488 return nil, nil, &url.URL{Path: path, RawQuery: u.RawQuery}
2491 return n, matches, nil
2494 // exactMatch reports whether the node's pattern exactly matches the path.
2495 // As a special case, if the node is nil, exactMatch return false.
2497 // Before wildcards were introduced, it was clear that an exact match meant
2498 // that the pattern and path were the same string. The only other possibility
2499 // was that a trailing-slash pattern, like "/", matched a path longer than
2502 // With wildcards, we define an inexact match as any one where a multi wildcard
2503 // matches a non-empty string. All other matches are exact.
2504 // For example, these are all exact matches:
2512 // The last case has a multi wildcard (implicitly), but the match is exact because
2513 // the wildcard matches the empty string.
2515 // Examples of matches that are not exact:
2520 func exactMatch(n *routingNode, path string) bool {
2524 // We can't directly implement the definition (empty match for multi
2525 // wildcard) because we don't record a match for anonymous multis.
2527 // If there is no multi, the match is exact.
2528 if !n.pattern.lastSegment().multi {
2532 // If the path doesn't end in a trailing slash, then the multi match
2534 if len(path) > 0 && path[len(path)-1] != '/' {
2537 // Only patterns ending in {$} or a multi wildcard can
2538 // match a path with a trailing slash.
2539 // For the match to be exact, the number of pattern
2540 // segments should be the same as the number of slashes in the path.
2541 // E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
2542 return len(n.pattern.segments) == strings.Count(path, "/")
2545 // ServeHTTP dispatches the request to the handler whose
2546 // pattern most closely matches the request URL.
2547 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2548 if r.RequestURI == "*" {
2549 if r.ProtoAtLeast(1, 1) {
2550 w.Header().Set("Connection", "close")
2552 w.WriteHeader(StatusBadRequest)
2555 h, _, pat, matches := mux.findHandler(r)
2561 // The four functions below all call register so that callerLocation
2562 // always refers to user code.
2564 // Handle registers the handler for the given pattern.
2565 // If a handler already exists for pattern, Handle panics.
2566 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2567 mux.register(pattern, handler)
2570 // HandleFunc registers the handler function for the given pattern.
2571 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2572 mux.register(pattern, HandlerFunc(handler))
2575 // Handle registers the handler for the given pattern in [DefaultServeMux].
2576 // The documentation for [ServeMux] explains how patterns are matched.
2577 func Handle(pattern string, handler Handler) {
2578 DefaultServeMux.register(pattern, handler)
2581 // HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
2582 // The documentation for [ServeMux] explains how patterns are matched.
2583 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2584 DefaultServeMux.register(pattern, HandlerFunc(handler))
2587 func (mux *ServeMux) register(pattern string, handler Handler) {
2588 if err := mux.registerErr(pattern, handler); err != nil {
2593 func (mux *ServeMux) registerErr(pattern string, handler Handler) error {
2595 return errors.New("http: invalid pattern")
2598 return errors.New("http: nil handler")
2600 if f, ok := handler.(HandlerFunc); ok && f == nil {
2601 return errors.New("http: nil handler")
2604 pat, err := parsePattern(pattern)
2606 return fmt.Errorf("parsing %q: %w", pattern, err)
2609 // Get the caller's location, for better conflict error messages.
2610 // Skip register and whatever calls it.
2611 _, file, line, ok := runtime.Caller(3)
2613 pat.loc = "unknown location"
2615 pat.loc = fmt.Sprintf("%s:%d", file, line)
2619 defer mux.mu.Unlock()
2620 // Check for conflict.
2621 // This makes a quadratic number of calls to conflictsWith: we check
2622 // each pattern against every other pattern.
2623 // TODO(jba): add indexing to speed this up.
2624 for _, pat2 := range mux.patterns {
2625 if pat.conflictsWith(pat2) {
2626 return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s)",
2627 pat, pat.loc, pat2, pat2.loc)
2630 mux.tree.addPattern(pat, handler)
2631 mux.patterns = append(mux.patterns, pat)
2635 // Serve accepts incoming HTTP connections on the listener l,
2636 // creating a new service goroutine for each. The service goroutines
2637 // read requests and then call handler to reply to them.
2639 // The handler is typically nil, in which case [DefaultServeMux] is used.
2641 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
2642 // connections and they were configured with "h2" in the TLS
2643 // Config.NextProtos.
2645 // Serve always returns a non-nil error.
2646 func Serve(l net.Listener, handler Handler) error {
2647 srv := &Server{Handler: handler}
2651 // ServeTLS accepts incoming HTTPS connections on the listener l,
2652 // creating a new service goroutine for each. The service goroutines
2653 // read requests and then call handler to reply to them.
2655 // The handler is typically nil, in which case [DefaultServeMux] is used.
2657 // Additionally, files containing a certificate and matching private key
2658 // for the server must be provided. If the certificate is signed by a
2659 // certificate authority, the certFile should be the concatenation
2660 // of the server's certificate, any intermediates, and the CA's certificate.
2662 // ServeTLS always returns a non-nil error.
2663 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2664 srv := &Server{Handler: handler}
2665 return srv.ServeTLS(l, certFile, keyFile)
2668 // A Server defines parameters for running an HTTP server.
2669 // The zero value for Server is a valid configuration.
2670 type Server struct {
2671 // Addr optionally specifies the TCP address for the server to listen on,
2672 // in the form "host:port". If empty, ":http" (port 80) is used.
2673 // The service names are defined in RFC 6335 and assigned by IANA.
2674 // See net.Dial for details of the address format.
2677 Handler Handler // handler to invoke, http.DefaultServeMux if nil
2679 // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
2680 // otherwise responds with 200 OK and Content-Length: 0.
2681 DisableGeneralOptionsHandler bool
2683 // TLSConfig optionally provides a TLS configuration for use
2684 // by ServeTLS and ListenAndServeTLS. Note that this value is
2685 // cloned by ServeTLS and ListenAndServeTLS, so it's not
2686 // possible to modify the configuration with methods like
2687 // tls.Config.SetSessionTicketKeys. To use
2688 // SetSessionTicketKeys, use Server.Serve with a TLS Listener
2690 TLSConfig *tls.Config
2692 // ReadTimeout is the maximum duration for reading the entire
2693 // request, including the body. A zero or negative value means
2694 // there will be no timeout.
2696 // Because ReadTimeout does not let Handlers make per-request
2697 // decisions on each request body's acceptable deadline or
2698 // upload rate, most users will prefer to use
2699 // ReadHeaderTimeout. It is valid to use them both.
2700 ReadTimeout time.Duration
2702 // ReadHeaderTimeout is the amount of time allowed to read
2703 // request headers. The connection's read deadline is reset
2704 // after reading the headers and the Handler can decide what
2705 // is considered too slow for the body. If ReadHeaderTimeout
2706 // is zero, the value of ReadTimeout is used. If both are
2707 // zero, there is no timeout.
2708 ReadHeaderTimeout time.Duration
2710 // WriteTimeout is the maximum duration before timing out
2711 // writes of the response. It is reset whenever a new
2712 // request's header is read. Like ReadTimeout, it does not
2713 // let Handlers make decisions on a per-request basis.
2714 // A zero or negative value means there will be no timeout.
2715 WriteTimeout time.Duration
2717 // IdleTimeout is the maximum amount of time to wait for the
2718 // next request when keep-alives are enabled. If IdleTimeout
2719 // is zero, the value of ReadTimeout is used. If both are
2720 // zero, there is no timeout.
2721 IdleTimeout time.Duration
2723 // MaxHeaderBytes controls the maximum number of bytes the
2724 // server will read parsing the request header's keys and
2725 // values, including the request line. It does not limit the
2726 // size of the request body.
2727 // If zero, DefaultMaxHeaderBytes is used.
2730 // TLSNextProto optionally specifies a function to take over
2731 // ownership of the provided TLS connection when an ALPN
2732 // protocol upgrade has occurred. The map key is the protocol
2733 // name negotiated. The Handler argument should be used to
2734 // handle HTTP requests and will initialize the Request's TLS
2735 // and RemoteAddr if not already set. The connection is
2736 // automatically closed when the function returns.
2737 // If TLSNextProto is not nil, HTTP/2 support is not enabled
2739 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2741 // ConnState specifies an optional callback function that is
2742 // called when a client connection changes state. See the
2743 // ConnState type and associated constants for details.
2744 ConnState func(net.Conn, ConnState)
2746 // ErrorLog specifies an optional logger for errors accepting
2747 // connections, unexpected behavior from handlers, and
2748 // underlying FileSystem errors.
2749 // If nil, logging is done via the log package's standard logger.
2750 ErrorLog *log.Logger
2752 // BaseContext optionally specifies a function that returns
2753 // the base context for incoming requests on this server.
2754 // The provided Listener is the specific Listener that's
2755 // about to start accepting requests.
2756 // If BaseContext is nil, the default is context.Background().
2757 // If non-nil, it must return a non-nil context.
2758 BaseContext func(net.Listener) context.Context
2760 // ConnContext optionally specifies a function that modifies
2761 // the context used for a new connection c. The provided ctx
2762 // is derived from the base context and has a ServerContextKey
2764 ConnContext func(ctx context.Context, c net.Conn) context.Context
2766 inShutdown atomic.Bool // true when server is in shutdown
2768 disableKeepAlives atomic.Bool
2769 nextProtoOnce sync.Once // guards setupHTTP2_* init
2770 nextProtoErr error // result of http2.ConfigureServer if used
2773 listeners map[*net.Listener]struct{}
2774 activeConn map[*conn]struct{}
2777 listenerGroup sync.WaitGroup
2780 // Close immediately closes all active net.Listeners and any
2781 // connections in state StateNew, StateActive, or StateIdle. For a
2782 // graceful shutdown, use Shutdown.
2784 // Close does not attempt to close (and does not even know about)
2785 // any hijacked connections, such as WebSockets.
2787 // Close returns any error returned from closing the Server's
2788 // underlying Listener(s).
2789 func (srv *Server) Close() error {
2790 srv.inShutdown.Store(true)
2792 defer srv.mu.Unlock()
2793 err := srv.closeListenersLocked()
2795 // Unlock srv.mu while waiting for listenerGroup.
2796 // The group Add and Done calls are made with srv.mu held,
2797 // to avoid adding a new listener in the window between
2798 // us setting inShutdown above and waiting here.
2800 srv.listenerGroup.Wait()
2803 for c := range srv.activeConn {
2805 delete(srv.activeConn, c)
2810 // shutdownPollIntervalMax is the max polling interval when checking
2811 // quiescence during Server.Shutdown. Polling starts with a small
2812 // interval and backs off to the max.
2813 // Ideally we could find a solution that doesn't involve polling,
2814 // but which also doesn't have a high runtime cost (and doesn't
2815 // involve any contentious mutexes), but that is left as an
2816 // exercise for the reader.
2817 const shutdownPollIntervalMax = 500 * time.Millisecond
2819 // Shutdown gracefully shuts down the server without interrupting any
2820 // active connections. Shutdown works by first closing all open
2821 // listeners, then closing all idle connections, and then waiting
2822 // indefinitely for connections to return to idle and then shut down.
2823 // If the provided context expires before the shutdown is complete,
2824 // Shutdown returns the context's error, otherwise it returns any
2825 // error returned from closing the Server's underlying Listener(s).
2827 // When Shutdown is called, Serve, ListenAndServe, and
2828 // ListenAndServeTLS immediately return ErrServerClosed. Make sure the
2829 // program doesn't exit and waits instead for Shutdown to return.
2831 // Shutdown does not attempt to close nor wait for hijacked
2832 // connections such as WebSockets. The caller of Shutdown should
2833 // separately notify such long-lived connections of shutdown and wait
2834 // for them to close, if desired. See RegisterOnShutdown for a way to
2835 // register shutdown notification functions.
2837 // Once Shutdown has been called on a server, it may not be reused;
2838 // future calls to methods such as Serve will return ErrServerClosed.
2839 func (srv *Server) Shutdown(ctx context.Context) error {
2840 srv.inShutdown.Store(true)
2843 lnerr := srv.closeListenersLocked()
2844 for _, f := range srv.onShutdown {
2848 srv.listenerGroup.Wait()
2850 pollIntervalBase := time.Millisecond
2851 nextPollInterval := func() time.Duration {
2853 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
2854 // Double and clamp for next time.
2855 pollIntervalBase *= 2
2856 if pollIntervalBase > shutdownPollIntervalMax {
2857 pollIntervalBase = shutdownPollIntervalMax
2862 timer := time.NewTimer(nextPollInterval())
2865 if srv.closeIdleConns() {
2872 timer.Reset(nextPollInterval())
2877 // RegisterOnShutdown registers a function to call on Shutdown.
2878 // This can be used to gracefully shutdown connections that have
2879 // undergone ALPN protocol upgrade or that have been hijacked.
2880 // This function should start protocol-specific graceful shutdown,
2881 // but should not wait for shutdown to complete.
2882 func (srv *Server) RegisterOnShutdown(f func()) {
2884 srv.onShutdown = append(srv.onShutdown, f)
2888 // closeIdleConns closes all idle connections and reports whether the
2889 // server is quiescent.
2890 func (s *Server) closeIdleConns() bool {
2894 for c := range s.activeConn {
2895 st, unixSec := c.getState()
2896 // Issue 22682: treat StateNew connections as if
2897 // they're idle if we haven't read the first request's
2898 // header in over 5 seconds.
2899 if st == StateNew && unixSec < time.Now().Unix()-5 {
2902 if st != StateIdle || unixSec == 0 {
2903 // Assume unixSec == 0 means it's a very new
2904 // connection, without state set yet.
2909 delete(s.activeConn, c)
2914 func (s *Server) closeListenersLocked() error {
2916 for ln := range s.listeners {
2917 if cerr := (*ln).Close(); cerr != nil && err == nil {
2924 // A ConnState represents the state of a client connection to a server.
2925 // It's used by the optional Server.ConnState hook.
2929 // StateNew represents a new connection that is expected to
2930 // send a request immediately. Connections begin at this
2931 // state and then transition to either StateActive or
2933 StateNew ConnState = iota
2935 // StateActive represents a connection that has read 1 or more
2936 // bytes of a request. The Server.ConnState hook for
2937 // StateActive fires before the request has entered a handler
2938 // and doesn't fire again until the request has been
2939 // handled. After the request is handled, the state
2940 // transitions to StateClosed, StateHijacked, or StateIdle.
2941 // For HTTP/2, StateActive fires on the transition from zero
2942 // to one active request, and only transitions away once all
2943 // active requests are complete. That means that ConnState
2944 // cannot be used to do per-request work; ConnState only notes
2945 // the overall state of the connection.
2948 // StateIdle represents a connection that has finished
2949 // handling a request and is in the keep-alive state, waiting
2950 // for a new request. Connections transition from StateIdle
2951 // to either StateActive or StateClosed.
2954 // StateHijacked represents a hijacked connection.
2955 // This is a terminal state. It does not transition to StateClosed.
2958 // StateClosed represents a closed connection.
2959 // This is a terminal state. Hijacked connections do not
2960 // transition to StateClosed.
2964 var stateName = map[ConnState]string{
2966 StateActive: "active",
2968 StateHijacked: "hijacked",
2969 StateClosed: "closed",
2972 func (c ConnState) String() string {
2976 // serverHandler delegates to either the server's Handler or
2977 // DefaultServeMux and also handles "OPTIONS *" requests.
2978 type serverHandler struct {
2982 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
2983 handler := sh.srv.Handler
2985 handler = DefaultServeMux
2987 if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
2988 handler = globalOptionsHandler{}
2991 handler.ServeHTTP(rw, req)
2994 // AllowQuerySemicolons returns a handler that serves requests by converting any
2995 // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
2997 // This restores the pre-Go 1.17 behavior of splitting query parameters on both
2998 // semicolons and ampersands. (See golang.org/issue/25192). Note that this
2999 // behavior doesn't match that of many proxies, and the mismatch can lead to
3002 // AllowQuerySemicolons should be invoked before Request.ParseForm is called.
3003 func AllowQuerySemicolons(h Handler) Handler {
3004 return HandlerFunc(func(w ResponseWriter, r *Request) {
3005 if strings.Contains(r.URL.RawQuery, ";") {
3008 r2.URL = new(url.URL)
3010 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
3018 // ListenAndServe listens on the TCP network address srv.Addr and then
3019 // calls Serve to handle requests on incoming connections.
3020 // Accepted connections are configured to enable TCP keep-alives.
3022 // If srv.Addr is blank, ":http" is used.
3024 // ListenAndServe always returns a non-nil error. After Shutdown or Close,
3025 // the returned error is ErrServerClosed.
3026 func (srv *Server) ListenAndServe() error {
3027 if srv.shuttingDown() {
3028 return ErrServerClosed
3034 ln, err := net.Listen("tcp", addr)
3038 return srv.Serve(ln)
3041 var testHookServerServe func(*Server, net.Listener) // used if non-nil
3043 // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
3044 // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
3045 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
3046 if srv.TLSConfig == nil {
3047 // Compatibility with Go 1.6:
3048 // If there's no TLSConfig, it's possible that the user just
3049 // didn't set it on the http.Server, but did pass it to
3050 // tls.NewListener and passed that listener to Serve.
3051 // So we should configure HTTP/2 (to set up srv.TLSNextProto)
3052 // in case the listener returns an "h2" *tls.Conn.
3055 // The user specified a TLSConfig on their http.Server.
3056 // In this, case, only configure HTTP/2 if their tls.Config
3057 // explicitly mentions "h2". Otherwise http2.ConfigureServer
3058 // would modify the tls.Config to add it, but they probably already
3059 // passed this tls.Config to tls.NewListener. And if they did,
3060 // it's too late anyway to fix it. It would only be potentially racy.
3062 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
3065 // ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
3066 // and ListenAndServeTLS methods after a call to Shutdown or Close.
3067 var ErrServerClosed = errors.New("http: Server closed")
3069 // Serve accepts incoming connections on the Listener l, creating a
3070 // new service goroutine for each. The service goroutines read requests and
3071 // then call srv.Handler to reply to them.
3073 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
3074 // connections and they were configured with "h2" in the TLS
3075 // Config.NextProtos.
3077 // Serve always returns a non-nil error and closes l.
3078 // After Shutdown or Close, the returned error is ErrServerClosed.
3079 func (srv *Server) Serve(l net.Listener) error {
3080 if fn := testHookServerServe; fn != nil {
3081 fn(srv, l) // call hook with unwrapped listener
3085 l = &onceCloseListener{Listener: l}
3088 if err := srv.setupHTTP2_Serve(); err != nil {
3092 if !srv.trackListener(&l, true) {
3093 return ErrServerClosed
3095 defer srv.trackListener(&l, false)
3097 baseCtx := context.Background()
3098 if srv.BaseContext != nil {
3099 baseCtx = srv.BaseContext(origListener)
3101 panic("BaseContext returned a nil context")
3105 var tempDelay time.Duration // how long to sleep on accept failure
3107 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3109 rw, err := l.Accept()
3111 if srv.shuttingDown() {
3112 return ErrServerClosed
3114 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3116 tempDelay = 5 * time.Millisecond
3120 if max := 1 * time.Second; tempDelay > max {
3123 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3124 time.Sleep(tempDelay)
3130 if cc := srv.ConnContext; cc != nil {
3131 connCtx = cc(connCtx, rw)
3133 panic("ConnContext returned nil")
3137 c := srv.newConn(rw)
3138 c.setState(c.rwc, StateNew, runHooks) // before Serve can return
3143 // ServeTLS accepts incoming connections on the Listener l, creating a
3144 // new service goroutine for each. The service goroutines perform TLS
3145 // setup and then read requests, calling srv.Handler to reply to them.
3147 // Files containing a certificate and matching private key for the
3148 // server must be provided if neither the Server's
3149 // TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
3150 // If the certificate is signed by a certificate authority, the
3151 // certFile should be the concatenation of the server's certificate,
3152 // any intermediates, and the CA's certificate.
3154 // ServeTLS always returns a non-nil error. After Shutdown or Close, the
3155 // returned error is ErrServerClosed.
3156 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3157 // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
3158 // before we clone it and create the TLS Listener.
3159 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3163 config := cloneTLSConfig(srv.TLSConfig)
3164 if !strSliceContains(config.NextProtos, "http/1.1") {
3165 config.NextProtos = append(config.NextProtos, "http/1.1")
3168 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3169 if !configHasCert || certFile != "" || keyFile != "" {
3171 config.Certificates = make([]tls.Certificate, 1)
3172 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3178 tlsListener := tls.NewListener(l, config)
3179 return srv.Serve(tlsListener)
3182 // trackListener adds or removes a net.Listener to the set of tracked
3185 // We store a pointer to interface in the map set, in case the
3186 // net.Listener is not comparable. This is safe because we only call
3187 // trackListener via Serve and can track+defer untrack the same
3188 // pointer to local variable there. We never need to compare a
3189 // Listener from another caller.
3191 // It reports whether the server is still up (not Shutdown or Closed).
3192 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3195 if s.listeners == nil {
3196 s.listeners = make(map[*net.Listener]struct{})
3199 if s.shuttingDown() {
3202 s.listeners[ln] = struct{}{}
3203 s.listenerGroup.Add(1)
3205 delete(s.listeners, ln)
3206 s.listenerGroup.Done()
3211 func (s *Server) trackConn(c *conn, add bool) {
3214 if s.activeConn == nil {
3215 s.activeConn = make(map[*conn]struct{})
3218 s.activeConn[c] = struct{}{}
3220 delete(s.activeConn, c)
3224 func (s *Server) idleTimeout() time.Duration {
3225 if s.IdleTimeout != 0 {
3226 return s.IdleTimeout
3228 return s.ReadTimeout
3231 func (s *Server) readHeaderTimeout() time.Duration {
3232 if s.ReadHeaderTimeout != 0 {
3233 return s.ReadHeaderTimeout
3235 return s.ReadTimeout
3238 func (s *Server) doKeepAlives() bool {
3239 return !s.disableKeepAlives.Load() && !s.shuttingDown()
3242 func (s *Server) shuttingDown() bool {
3243 return s.inShutdown.Load()
3246 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
3247 // By default, keep-alives are always enabled. Only very
3248 // resource-constrained environments or servers in the process of
3249 // shutting down should disable them.
3250 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3252 srv.disableKeepAlives.Store(false)
3255 srv.disableKeepAlives.Store(true)
3257 // Close idle HTTP/1 conns:
3258 srv.closeIdleConns()
3260 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
3263 func (s *Server) logf(format string, args ...any) {
3264 if s.ErrorLog != nil {
3265 s.ErrorLog.Printf(format, args...)
3267 log.Printf(format, args...)
3271 // logf prints to the ErrorLog of the *Server associated with request r
3272 // via ServerContextKey. If there's no associated server, or if ErrorLog
3273 // is nil, logging is done via the log package's standard logger.
3274 func logf(r *Request, format string, args ...any) {
3275 s, _ := r.Context().Value(ServerContextKey).(*Server)
3276 if s != nil && s.ErrorLog != nil {
3277 s.ErrorLog.Printf(format, args...)
3279 log.Printf(format, args...)
3283 // ListenAndServe listens on the TCP network address addr and then calls
3284 // Serve with handler to handle requests on incoming connections.
3285 // Accepted connections are configured to enable TCP keep-alives.
3287 // The handler is typically nil, in which case [DefaultServeMux] is used.
3289 // ListenAndServe always returns a non-nil error.
3290 func ListenAndServe(addr string, handler Handler) error {
3291 server := &Server{Addr: addr, Handler: handler}
3292 return server.ListenAndServe()
3295 // ListenAndServeTLS acts identically to [ListenAndServe], except that it
3296 // expects HTTPS connections. Additionally, files containing a certificate and
3297 // matching private key for the server must be provided. If the certificate
3298 // is signed by a certificate authority, the certFile should be the concatenation
3299 // of the server's certificate, any intermediates, and the CA's certificate.
3300 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3301 server := &Server{Addr: addr, Handler: handler}
3302 return server.ListenAndServeTLS(certFile, keyFile)
3305 // ListenAndServeTLS listens on the TCP network address srv.Addr and
3306 // then calls ServeTLS to handle requests on incoming TLS connections.
3307 // Accepted connections are configured to enable TCP keep-alives.
3309 // Filenames containing a certificate and matching private key for the
3310 // server must be provided if neither the Server's TLSConfig.Certificates
3311 // nor TLSConfig.GetCertificate are populated. If the certificate is
3312 // signed by a certificate authority, the certFile should be the
3313 // concatenation of the server's certificate, any intermediates, and
3314 // the CA's certificate.
3316 // If srv.Addr is blank, ":https" is used.
3318 // ListenAndServeTLS always returns a non-nil error. After Shutdown or
3319 // Close, the returned error is ErrServerClosed.
3320 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3321 if srv.shuttingDown() {
3322 return ErrServerClosed
3329 ln, err := net.Listen("tcp", addr)
3336 return srv.ServeTLS(ln, certFile, keyFile)
3339 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
3340 // srv and reports whether there was an error setting it up. If it is
3341 // not configured for policy reasons, nil is returned.
3342 func (srv *Server) setupHTTP2_ServeTLS() error {
3343 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3344 return srv.nextProtoErr
3347 // setupHTTP2_Serve is called from (*Server).Serve and conditionally
3348 // configures HTTP/2 on srv using a more conservative policy than
3349 // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
3350 // and may be called concurrently. See shouldConfigureHTTP2ForServe.
3352 // The tests named TestTransportAutomaticHTTP2* and
3353 // TestConcurrentServerServe in server_test.go demonstrate some
3354 // of the supported use cases and motivations.
3355 func (srv *Server) setupHTTP2_Serve() error {
3356 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3357 return srv.nextProtoErr
3360 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3361 if srv.shouldConfigureHTTP2ForServe() {
3362 srv.onceSetNextProtoDefaults()
3366 var http2server = godebug.New("http2server")
3368 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
3369 // configured otherwise. (by setting srv.TLSNextProto non-nil)
3370 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
3371 func (srv *Server) onceSetNextProtoDefaults() {
3372 if omitBundledHTTP2 {
3375 if http2server.Value() == "0" {
3376 http2server.IncNonDefault()
3379 // Enable HTTP/2 by default if the user hasn't otherwise
3380 // configured their TLSNextProto map.
3381 if srv.TLSNextProto == nil {
3382 conf := &http2Server{
3383 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3385 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3389 // TimeoutHandler returns a Handler that runs h with the given time limit.
3391 // The new Handler calls h.ServeHTTP to handle each request, but if a
3392 // call runs for longer than its time limit, the handler responds with
3393 // a 503 Service Unavailable error and the given message in its body.
3394 // (If msg is empty, a suitable default message will be sent.)
3395 // After such a timeout, writes by h to its ResponseWriter will return
3396 // ErrHandlerTimeout.
3398 // TimeoutHandler supports the Pusher interface but does not support
3399 // the Hijacker or Flusher interfaces.
3400 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3401 return &timeoutHandler{
3408 // ErrHandlerTimeout is returned on ResponseWriter Write calls
3409 // in handlers which have timed out.
3410 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3412 type timeoutHandler struct {
3417 // When set, no context will be created and this context will
3419 testContext context.Context
3422 func (h *timeoutHandler) errorBody() string {
3426 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3429 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3430 ctx := h.testContext
3432 var cancelCtx context.CancelFunc
3433 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3436 r = r.WithContext(ctx)
3437 done := make(chan struct{})
3438 tw := &timeoutWriter{
3443 panicChan := make(chan any, 1)
3446 if p := recover(); p != nil {
3450 h.handler.ServeHTTP(tw, r)
3454 case p := <-panicChan:
3458 defer tw.mu.Unlock()
3460 for k, vv := range tw.h {
3463 if !tw.wroteHeader {
3466 w.WriteHeader(tw.code)
3467 w.Write(tw.wbuf.Bytes())
3470 defer tw.mu.Unlock()
3471 switch err := ctx.Err(); err {
3472 case context.DeadlineExceeded:
3473 w.WriteHeader(StatusServiceUnavailable)
3474 io.WriteString(w, h.errorBody())
3475 tw.err = ErrHandlerTimeout
3477 w.WriteHeader(StatusServiceUnavailable)
3483 type timeoutWriter struct {
3495 var _ Pusher = (*timeoutWriter)(nil)
3497 // Push implements the Pusher interface.
3498 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3499 if pusher, ok := tw.w.(Pusher); ok {
3500 return pusher.Push(target, opts)
3502 return ErrNotSupported
3505 func (tw *timeoutWriter) Header() Header { return tw.h }
3507 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3509 defer tw.mu.Unlock()
3513 if !tw.wroteHeader {
3514 tw.writeHeaderLocked(StatusOK)
3516 return tw.wbuf.Write(p)
3519 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3520 checkWriteHeaderCode(code)
3525 case tw.wroteHeader:
3527 caller := relevantCaller()
3528 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3531 tw.wroteHeader = true
3536 func (tw *timeoutWriter) WriteHeader(code int) {
3538 defer tw.mu.Unlock()
3539 tw.writeHeaderLocked(code)
3542 // onceCloseListener wraps a net.Listener, protecting it from
3543 // multiple Close calls.
3544 type onceCloseListener struct {
3550 func (oc *onceCloseListener) Close() error {
3551 oc.once.Do(oc.close)
3555 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3557 // globalOptionsHandler responds to "OPTIONS *" requests.
3558 type globalOptionsHandler struct{}
3560 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3561 w.Header().Set("Content-Length", "0")
3562 if r.ContentLength != 0 {
3563 // Read up to 4KB of OPTIONS body (as mentioned in the
3564 // spec as being reserved for future use), but anything
3565 // over that is considered a waste of server resources
3566 // (or an attack) and we abort and close the connection,
3567 // courtesy of MaxBytesReader's EOF behavior.
3568 mb := MaxBytesReader(w, r.Body, 4<<10)
3569 io.Copy(io.Discard, mb)
3573 // initALPNRequest is an HTTP handler that initializes certain
3574 // uninitialized fields in its *Request. Such partially-initialized
3575 // Requests come from ALPN protocol handlers.
3576 type initALPNRequest struct {
3582 // BaseContext is an exported but unadvertised http.Handler method
3583 // recognized by x/net/http2 to pass down a context; the TLSNextProto
3584 // API predates context support so we shoehorn through the only
3585 // interface we have available.
3586 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3588 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3590 req.TLS = &tls.ConnectionState{}
3591 *req.TLS = h.c.ConnectionState()
3593 if req.Body == nil {
3596 if req.RemoteAddr == "" {
3597 req.RemoteAddr = h.c.RemoteAddr().String()
3599 h.h.ServeHTTP(rw, req)
3602 // loggingConn is used for debugging.
3603 type loggingConn struct {
3609 uniqNameMu sync.Mutex
3610 uniqNameNext = make(map[string]int)
3613 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3615 defer uniqNameMu.Unlock()
3616 uniqNameNext[baseName]++
3617 return &loggingConn{
3618 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3623 func (c *loggingConn) Write(p []byte) (n int, err error) {
3624 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3625 n, err = c.Conn.Write(p)
3626 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3630 func (c *loggingConn) Read(p []byte) (n int, err error) {
3631 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3632 n, err = c.Conn.Read(p)
3633 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3637 func (c *loggingConn) Close() (err error) {
3638 log.Printf("%s.Close() = ...", c.name)
3639 err = c.Conn.Close()
3640 log.Printf("%s.Close() = %v", c.name, err)
3644 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
3645 // It only contains one field (and a pointer field at that), so it
3646 // fits in an interface value without an extra allocation.
3647 type checkConnErrorWriter struct {
3651 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3652 n, err = w.c.rwc.Write(p)
3653 if err != nil && w.c.werr == nil {
3660 func numLeadingCRorLF(v []byte) (n int) {
3661 for _, b := range v {
3662 if b == '\r' || b == '\n' {
3672 func strSliceContains(ss []string, s string) bool {
3673 for _, v := range ss {
3681 // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
3682 // looks like it might've been a misdirected plaintext HTTP request.
3683 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3684 switch string(hdr[:]) {
3685 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3691 // MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.
3692 func MaxBytesHandler(h Handler, n int64) Handler {
3693 return HandlerFunc(func(w ResponseWriter, r *Request) {
3695 r2.Body = MaxBytesReader(w, r.Body, n)