1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // HTTP server. See RFC 7230 through 7235.
33 "golang.org/x/net/http/httpguts"
36 // Errors used by the HTTP server.
38 // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
39 // when the HTTP method or response code does not permit a
41 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
43 // ErrHijacked is returned by ResponseWriter.Write calls when
44 // the underlying connection has been hijacked using the
45 // Hijacker interface. A zero-byte write on a hijacked
46 // connection will return ErrHijacked without any other side
48 ErrHijacked = errors.New("http: connection has been hijacked")
50 // ErrContentLength is returned by ResponseWriter.Write calls
51 // when a Handler set a Content-Length response header with a
52 // declared size and then attempted to write more bytes than
54 ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
56 // Deprecated: ErrWriteAfterFlush is no longer returned by
57 // anything in the net/http package. Callers should not
58 // compare errors against this variable.
59 ErrWriteAfterFlush = errors.New("unused")
62 // A Handler responds to an HTTP request.
64 // ServeHTTP should write reply headers and data to the ResponseWriter
65 // and then return. Returning signals that the request is finished; it
66 // is not valid to use the ResponseWriter or read from the
67 // Request.Body after or concurrently with the completion of the
70 // Depending on the HTTP client software, HTTP protocol version, and
71 // any intermediaries between the client and the Go server, it may not
72 // be possible to read from the Request.Body after writing to the
73 // ResponseWriter. Cautious handlers should read the Request.Body
74 // first, and then reply.
76 // Except for reading the body, handlers should not modify the
79 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
80 // that the effect of the panic was isolated to the active request.
81 // It recovers the panic, logs a stack trace to the server error log,
82 // and either closes the network connection or sends an HTTP/2
83 // RST_STREAM, depending on the HTTP protocol. To abort a handler so
84 // the client sees an interrupted response but the server doesn't log
85 // an error, panic with the value ErrAbortHandler.
86 type Handler interface {
87 ServeHTTP(ResponseWriter, *Request)
90 // A ResponseWriter interface is used by an HTTP handler to
91 // construct an HTTP response.
93 // A ResponseWriter may not be used after the Handler.ServeHTTP method
95 type ResponseWriter interface {
96 // Header returns the header map that will be sent by
97 // WriteHeader. The Header map also is the mechanism with which
98 // Handlers can set HTTP trailers.
100 // Changing the header map after a call to WriteHeader (or
101 // Write) has no effect unless the HTTP status code was of the
102 // 1xx class or the modified headers are trailers.
104 // There are two ways to set Trailers. The preferred way is to
105 // predeclare in the headers which trailers you will later
106 // send by setting the "Trailer" header to the names of the
107 // trailer keys which will come later. In this case, those
108 // keys of the Header map are treated as if they were
109 // trailers. See the example. The second way, for trailer
110 // keys not known to the Handler until after the first Write,
111 // is to prefix the Header map keys with the TrailerPrefix
112 // constant value. See TrailerPrefix.
114 // To suppress automatic response headers (such as "Date"), set
115 // their value to nil.
118 // Write writes the data to the connection as part of an HTTP reply.
120 // If WriteHeader has not yet been called, Write calls
121 // WriteHeader(http.StatusOK) before writing the data. If the Header
122 // does not contain a Content-Type line, Write adds a Content-Type set
123 // to the result of passing the initial 512 bytes of written data to
124 // DetectContentType. Additionally, if the total size of all written
125 // data is under a few KB and there are no Flush calls, the
126 // Content-Length header is added automatically.
128 // Depending on the HTTP protocol version and the client, calling
129 // Write or WriteHeader may prevent future reads on the
130 // Request.Body. For HTTP/1.x requests, handlers should read any
131 // needed request body data before writing the response. Once the
132 // headers have been flushed (due to either an explicit Flusher.Flush
133 // call or writing enough data to trigger a flush), the request body
134 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
135 // handlers to continue to read the request body while concurrently
136 // writing the response. However, such behavior may not be supported
137 // by all HTTP/2 clients. Handlers should read before writing if
138 // possible to maximize compatibility.
139 Write([]byte) (int, error)
141 // WriteHeader sends an HTTP response header with the provided
144 // If WriteHeader is not called explicitly, the first call to Write
145 // will trigger an implicit WriteHeader(http.StatusOK).
146 // Thus explicit calls to WriteHeader are mainly used to
147 // send error codes or 1xx informational responses.
149 // The provided code must be a valid HTTP 1xx-5xx status code.
150 // Any number of 1xx headers may be written, followed by at most
151 // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
152 // headers may be buffered. Use the Flusher interface to send
153 // buffered data. The header map is cleared when 2xx-5xx headers are
154 // sent, but not with 1xx headers.
156 // The server will automatically send a 100 (Continue) header
157 // on the first read from the request body if the request has
158 // an "Expect: 100-continue" header.
159 WriteHeader(statusCode int)
162 // The Flusher interface is implemented by ResponseWriters that allow
163 // an HTTP handler to flush buffered data to the client.
165 // The default HTTP/1.x and HTTP/2 ResponseWriter implementations
166 // support Flusher, but ResponseWriter wrappers may not. Handlers
167 // should always test for this ability at runtime.
169 // Note that even for ResponseWriters that support Flush,
170 // if the client is connected through an HTTP proxy,
171 // the buffered data may not reach the client until the response
173 type Flusher interface {
174 // Flush sends any buffered data to the client.
178 // The Hijacker interface is implemented by ResponseWriters that allow
179 // an HTTP handler to take over the connection.
181 // The default ResponseWriter for HTTP/1.x connections supports
182 // Hijacker, but HTTP/2 connections intentionally do not.
183 // ResponseWriter wrappers may also not support Hijacker. Handlers
184 // should always test for this ability at runtime.
185 type Hijacker interface {
186 // Hijack lets the caller take over the connection.
187 // After a call to Hijack the HTTP server library
188 // will not do anything else with the connection.
190 // It becomes the caller's responsibility to manage
191 // and close the connection.
193 // The returned net.Conn may have read or write deadlines
194 // already set, depending on the configuration of the
195 // Server. It is the caller's responsibility to set
196 // or clear those deadlines as needed.
198 // The returned bufio.Reader may contain unprocessed buffered
199 // data from the client.
201 // After a call to Hijack, the original Request.Body must not
202 // be used. The original Request's Context remains valid and
203 // is not canceled until the Request's ServeHTTP method
205 Hijack() (net.Conn, *bufio.ReadWriter, error)
208 // The CloseNotifier interface is implemented by ResponseWriters which
209 // allow detecting when the underlying connection has gone away.
211 // This mechanism can be used to cancel long operations on the server
212 // if the client has disconnected before the response is ready.
214 // Deprecated: the CloseNotifier interface predates Go's context package.
215 // New code should use Request.Context instead.
216 type CloseNotifier interface {
217 // CloseNotify returns a channel that receives at most a
218 // single value (true) when the client connection has gone
221 // CloseNotify may wait to notify until Request.Body has been
224 // After the Handler has returned, there is no guarantee
225 // that the channel receives a value.
227 // If the protocol is HTTP/1.1 and CloseNotify is called while
228 // processing an idempotent request (such a GET) while
229 // HTTP/1.1 pipelining is in use, the arrival of a subsequent
230 // pipelined request may cause a value to be sent on the
231 // returned channel. In practice HTTP/1.1 pipelining is not
232 // enabled in browsers and not seen often in the wild. If this
233 // is a problem, use HTTP/2 or only use CloseNotify on methods
235 CloseNotify() <-chan bool
239 // ServerContextKey is a context key. It can be used in HTTP
240 // handlers with Context.Value to access the server that
241 // started the handler. The associated value will be of
243 ServerContextKey = &contextKey{"http-server"}
245 // LocalAddrContextKey is a context key. It can be used in
246 // HTTP handlers with Context.Value to access the local
247 // address the connection arrived on.
248 // The associated value will be of type net.Addr.
249 LocalAddrContextKey = &contextKey{"local-addr"}
252 // A conn represents the server side of an HTTP connection.
254 // server is the server on which the connection arrived.
255 // Immutable; never nil.
258 // cancelCtx cancels the connection-level context.
259 cancelCtx context.CancelFunc
261 // rwc is the underlying network connection.
262 // This is never wrapped by other types and is the value given out
263 // to CloseNotifier callers. It is usually of type *net.TCPConn or
267 // remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
268 // inside the Listener's Accept goroutine, as some implementations block.
269 // It is populated immediately inside the (*conn).serve goroutine.
270 // This is the value of a Handler's (*Request).RemoteAddr.
273 // tlsState is the TLS connection state when using TLS.
274 // nil means not TLS.
275 tlsState *tls.ConnectionState
277 // werr is set to the first write error to rwc.
278 // It is set via checkConnErrorWriter{w}, where bufw writes.
281 // r is bufr's read source. It's a wrapper around rwc that provides
282 // io.LimitedReader-style limiting (while reading request headers)
283 // and functionality to support CloseNotifier. See *connReader docs.
286 // bufr reads from r.
289 // bufw writes to checkConnErrorWriter{c}, which populates werr on error.
292 // lastMethod is the method of the most recent request
293 // on this connection, if any.
296 curReq atomic.Pointer[response] // (which has a Request in it)
298 curState atomic.Uint64 // packed (unixtime<<8|uint8(ConnState))
300 // mu guards hijackedv
303 // hijackedv is whether this connection has been hijacked
304 // by a Handler with the Hijacker interface.
305 // It is guarded by mu.
309 func (c *conn) hijacked() bool {
315 // c.mu must be held.
316 func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
318 return nil, nil, ErrHijacked
320 c.r.abortPendingRead()
324 rwc.SetDeadline(time.Time{})
326 buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
328 if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
329 return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
332 c.setState(rwc, StateHijacked, runHooks)
336 // This should be >= 512 bytes for DetectContentType,
337 // but otherwise it's somewhat arbitrary.
338 const bufferBeforeChunkingSize = 2048
340 // chunkWriter writes to a response's conn buffer, and is the writer
341 // wrapped by the response.w buffered writer.
343 // chunkWriter also is responsible for finalizing the Header, including
344 // conditionally setting the Content-Type and setting a Content-Length
345 // in cases where the handler's final output is smaller than the buffer
346 // size. It also conditionally adds chunk headers, when in chunking mode.
348 // See the comment above (*response).Write for the entire write flow.
349 type chunkWriter struct {
352 // header is either nil or a deep clone of res.handlerHeader
353 // at the time of res.writeHeader, if res.writeHeader is
354 // called and extra buffering is being done to calculate
355 // Content-Type and/or Content-Length.
358 // wroteHeader tells whether the header's been written to "the
359 // wire" (or rather: w.conn.buf). this is unlike
360 // (*response).wroteHeader, which tells only whether it was
361 // logically written.
364 // set by the writeHeader method:
365 chunking bool // using chunked transfer encoding for reply body
369 crlf = []byte("\r\n")
370 colonSpace = []byte(": ")
373 func (cw *chunkWriter) Write(p []byte) (n int, err error) {
377 if cw.res.req.Method == "HEAD" {
382 _, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
384 cw.res.conn.rwc.Close()
388 n, err = cw.res.conn.bufw.Write(p)
389 if cw.chunking && err == nil {
390 _, err = cw.res.conn.bufw.Write(crlf)
393 cw.res.conn.rwc.Close()
398 func (cw *chunkWriter) flush() error {
402 return cw.res.conn.bufw.Flush()
405 func (cw *chunkWriter) close() {
410 bw := cw.res.conn.bufw // conn's bufio writer
411 // zero chunk to mark EOF
412 bw.WriteString("0\r\n")
413 if trailers := cw.res.finalTrailers(); trailers != nil {
414 trailers.Write(bw) // the writer handles noting errors
416 // final blank line after the trailers (whether
418 bw.WriteString("\r\n")
422 // A response represents the server side of an HTTP response.
423 type response struct {
425 req *Request // request for this response
426 reqBody io.ReadCloser
427 cancelCtx context.CancelFunc // when ServeHTTP exits
428 wroteHeader bool // a non-1xx header has been (logically) written
429 wroteContinue bool // 100 Continue response was written
430 wants10KeepAlive bool // HTTP/1.0 w/ Connection "keep-alive"
431 wantsClose bool // HTTP request has Connection "close"
433 // canWriteContinue is an atomic boolean that says whether or
434 // not a 100 Continue header can be written to the
436 // writeContinueMu must be held while writing the header.
437 // These two fields together synchronize the body reader (the
438 // expectContinueReader, which wants to write 100 Continue)
439 // against the main writer.
440 canWriteContinue atomic.Bool
441 writeContinueMu sync.Mutex
443 w *bufio.Writer // buffers output in chunks to chunkWriter
446 // handlerHeader is the Header that Handlers get access to,
447 // which may be retained and mutated even after WriteHeader.
448 // handlerHeader is copied into cw.header at WriteHeader
449 // time, and privately mutated thereafter.
451 calledHeader bool // handler accessed handlerHeader via Header
453 written int64 // number of bytes written in body
454 contentLength int64 // explicitly-declared Content-Length; or -1
455 status int // status code passed to WriteHeader
457 // close connection after this reply. set on request and
458 // updated after response from handler if there's a
459 // "Connection: keep-alive" response header and a
463 // requestBodyLimitHit is set by requestTooLarge when
464 // maxBytesReader hits its max size. It is checked in
465 // WriteHeader, to make sure we don't consume the
466 // remaining request body to try to advance to the next HTTP
467 // request. Instead, when this is set, we stop reading
468 // subsequent requests on this connection and stop reading
470 requestBodyLimitHit bool
472 // trailers are the headers to be sent after the handler
473 // finishes writing the body. This field is initialized from
474 // the Trailer response header when the response header is
478 handlerDone atomic.Bool // set true when the handler exits
480 // Buffers for Date, Content-Length, and status code
481 dateBuf [len(TimeFormat)]byte
485 // closeNotifyCh is the channel returned by CloseNotify.
486 // TODO(bradfitz): this is currently (for Go 1.8) always
487 // non-nil. Make this lazily-created again as it used to be?
488 closeNotifyCh chan bool
489 didCloseNotify atomic.Bool // atomic (only false->true winner should send)
492 func (c *response) SetReadDeadline(deadline time.Time) error {
493 return c.conn.rwc.SetReadDeadline(deadline)
496 func (c *response) SetWriteDeadline(deadline time.Time) error {
497 return c.conn.rwc.SetWriteDeadline(deadline)
500 // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
501 // that, if present, signals that the map entry is actually for
502 // the response trailers, and not the response headers. The prefix
503 // is stripped after the ServeHTTP call finishes and the values are
504 // sent in the trailers.
506 // This mechanism is intended only for trailers that are not known
507 // prior to the headers being written. If the set of trailers is fixed
508 // or known before the header is written, the normal Go trailers mechanism
511 // https://pkg.go.dev/net/http#ResponseWriter
512 // https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
513 const TrailerPrefix = "Trailer:"
515 // finalTrailers is called after the Handler exits and returns a non-nil
516 // value if the Handler set any trailers.
517 func (w *response) finalTrailers() Header {
519 for k, vv := range w.handlerHeader {
520 if kk, found := strings.CutPrefix(k, TrailerPrefix); found {
527 for _, k := range w.trailers {
531 for _, v := range w.handlerHeader[k] {
538 // declareTrailer is called for each Trailer header when the
539 // response header is written. It notes that a header will need to be
540 // written in the trailers at the end of the response.
541 func (w *response) declareTrailer(k string) {
542 k = CanonicalHeaderKey(k)
543 if !httpguts.ValidTrailerHeader(k) {
544 // Forbidden by RFC 7230, section 4.1.2
547 w.trailers = append(w.trailers, k)
550 // requestTooLarge is called by maxBytesReader when too much input has
551 // been read from the client.
552 func (w *response) requestTooLarge() {
553 w.closeAfterReply = true
554 w.requestBodyLimitHit = true
556 w.Header().Set("Connection", "close")
560 // writerOnly hides an io.Writer value's optional ReadFrom method
562 type writerOnly struct {
566 // ReadFrom is here to optimize copying from an *os.File regular file
567 // to a *net.TCPConn with sendfile, or from a supported src type such
568 // as a *net.TCPConn on Linux with splice.
569 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
570 bufp := copyBufPool.Get().(*[]byte)
572 defer copyBufPool.Put(bufp)
574 // Our underlying w.conn.rwc is usually a *TCPConn (with its
575 // own ReadFrom method). If not, just fall back to the normal
577 rf, ok := w.conn.rwc.(io.ReaderFrom)
579 return io.CopyBuffer(writerOnly{w}, src, buf)
582 // Copy the first sniffLen bytes before switching to ReadFrom.
583 // This ensures we don't start writing the response before the
584 // source is available (see golang.org/issue/5660) and provides
585 // enough bytes to perform Content-Type sniffing when required.
586 if !w.cw.wroteHeader {
587 n0, err := io.CopyBuffer(writerOnly{w}, io.LimitReader(src, sniffLen), buf)
589 if err != nil || n0 < sniffLen {
594 w.w.Flush() // get rid of any previous writes
595 w.cw.flush() // make sure Header is written; flush data to rwc
597 // Now that cw has been flushed, its chunking field is guaranteed initialized.
598 if !w.cw.chunking && w.bodyAllowed() {
599 n0, err := rf.ReadFrom(src)
605 n0, err := io.CopyBuffer(writerOnly{w}, src, buf)
610 // debugServerConnections controls whether all server connections are wrapped
611 // with a verbose logging wrapper.
612 const debugServerConnections = false
614 // Create new connection from rwc.
615 func (srv *Server) newConn(rwc net.Conn) *conn {
620 if debugServerConnections {
621 c.rwc = newLoggingConn("server", c.rwc)
626 type readResult struct {
630 b byte // byte read, if n == 1
633 // connReader is the io.Reader wrapper used by *conn. It combines a
634 // selectively-activated io.LimitedReader (to bound request header
635 // read sizes) with support for selectively keeping an io.Reader.Read
636 // call blocked in a background goroutine to wait for activity and
637 // trigger a CloseNotifier channel.
638 type connReader struct {
641 mu sync.Mutex // guards following
646 aborted bool // set true before conn.rwc deadline is set to past
647 remain int64 // bytes remaining
650 func (cr *connReader) lock() {
653 cr.cond = sync.NewCond(&cr.mu)
657 func (cr *connReader) unlock() { cr.mu.Unlock() }
659 func (cr *connReader) startBackgroundRead() {
663 panic("invalid concurrent Body.Read call")
669 cr.conn.rwc.SetReadDeadline(time.Time{})
670 go cr.backgroundRead()
673 func (cr *connReader) backgroundRead() {
674 n, err := cr.conn.rwc.Read(cr.byteBuf[:])
678 // We were past the end of the previous request's body already
679 // (since we wouldn't be in a background read otherwise), so
680 // this is a pipelined HTTP request. Prior to Go 1.11 we used to
681 // send on the CloseNotify channel and cancel the context here,
682 // but the behavior was documented as only "may", and we only
683 // did that because that's how CloseNotify accidentally behaved
684 // in very early Go releases prior to context support. Once we
685 // added context support, people used a Handler's
686 // Request.Context() and passed it along. Having that context
687 // cancel on pipelined HTTP requests caused problems.
688 // Fortunately, almost nothing uses HTTP/1.x pipelining.
689 // Unfortunately, apt-get does, or sometimes does.
690 // New Go 1.11 behavior: don't fire CloseNotify or cancel
691 // contexts on pipelined requests. Shouldn't affect people, but
692 // fixes cases like Issue 23921. This does mean that a client
693 // closing their TCP connection after sending a pipelined
694 // request won't cancel the context, but we'll catch that on any
695 // write failure (in checkConnErrorWriter.Write).
696 // If the server never writes, yes, there are still contrived
697 // server & client behaviors where this fails to ever cancel the
698 // context, but that's kinda why HTTP/1.x pipelining died
701 if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
702 // Ignore this error. It's the expected error from
703 // another goroutine calling abortPendingRead.
704 } else if err != nil {
705 cr.handleReadError(err)
713 func (cr *connReader) abortPendingRead() {
720 cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
724 cr.conn.rwc.SetReadDeadline(time.Time{})
727 func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
728 func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 }
729 func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 }
731 // handleReadError is called whenever a Read from the client returns a
734 // The provided non-nil err is almost always io.EOF or a "use of
735 // closed network connection". In any case, the error is not
736 // particularly interesting, except perhaps for debugging during
737 // development. Any error means the connection is dead and we should
740 // It may be called from multiple goroutines.
741 func (cr *connReader) handleReadError(_ error) {
746 // may be called from multiple goroutines.
747 func (cr *connReader) closeNotify() {
748 res := cr.conn.curReq.Load()
749 if res != nil && !res.didCloseNotify.Swap(true) {
750 res.closeNotifyCh <- true
754 func (cr *connReader) Read(p []byte) (n int, err error) {
758 if cr.conn.hijacked() {
759 panic("invalid Body.Read call. After hijacked, the original Request must not be used")
761 panic("invalid concurrent Body.Read call")
763 if cr.hitReadLimit() {
771 if int64(len(p)) > cr.remain {
782 n, err = cr.conn.rwc.Read(p)
787 cr.handleReadError(err)
789 cr.remain -= int64(n)
797 bufioReaderPool sync.Pool
798 bufioWriter2kPool sync.Pool
799 bufioWriter4kPool sync.Pool
802 var copyBufPool = sync.Pool{
804 b := make([]byte, 32*1024)
809 func bufioWriterPool(size int) *sync.Pool {
812 return &bufioWriter2kPool
814 return &bufioWriter4kPool
819 func newBufioReader(r io.Reader) *bufio.Reader {
820 if v := bufioReaderPool.Get(); v != nil {
821 br := v.(*bufio.Reader)
825 // Note: if this reader size is ever changed, update
826 // TestHandlerBodyClose's assumptions.
827 return bufio.NewReader(r)
830 func putBufioReader(br *bufio.Reader) {
832 bufioReaderPool.Put(br)
835 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
836 pool := bufioWriterPool(size)
838 if v := pool.Get(); v != nil {
839 bw := v.(*bufio.Writer)
844 return bufio.NewWriterSize(w, size)
847 func putBufioWriter(bw *bufio.Writer) {
849 if pool := bufioWriterPool(bw.Available()); pool != nil {
854 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
855 // in an HTTP request.
856 // This can be overridden by setting Server.MaxHeaderBytes.
857 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
859 func (srv *Server) maxHeaderBytes() int {
860 if srv.MaxHeaderBytes > 0 {
861 return srv.MaxHeaderBytes
863 return DefaultMaxHeaderBytes
866 func (srv *Server) initialReadLimitSize() int64 {
867 return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
870 // tlsHandshakeTimeout returns the time limit permitted for the TLS
871 // handshake, or zero for unlimited.
873 // It returns the minimum of any positive ReadHeaderTimeout,
874 // ReadTimeout, or WriteTimeout.
875 func (srv *Server) tlsHandshakeTimeout() time.Duration {
876 var ret time.Duration
877 for _, v := range [...]time.Duration{
878 srv.ReadHeaderTimeout,
885 if ret == 0 || v < ret {
892 // wrapper around io.ReadCloser which on first read, sends an
893 // HTTP/1.1 100 Continue header
894 type expectContinueReader struct {
896 readCloser io.ReadCloser
901 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
902 if ecr.closed.Load() {
903 return 0, ErrBodyReadAfterClose
906 if !w.wroteContinue && w.canWriteContinue.Load() && !w.conn.hijacked() {
907 w.wroteContinue = true
908 w.writeContinueMu.Lock()
909 if w.canWriteContinue.Load() {
910 w.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
912 w.canWriteContinue.Store(false)
914 w.writeContinueMu.Unlock()
916 n, err = ecr.readCloser.Read(p)
918 ecr.sawEOF.Store(true)
923 func (ecr *expectContinueReader) Close() error {
924 ecr.closed.Store(true)
925 return ecr.readCloser.Close()
928 // TimeFormat is the time format to use when generating times in HTTP
929 // headers. It is like time.RFC1123 but hard-codes GMT as the time
930 // zone. The time being formatted must be in UTC for Format to
931 // generate the correct format.
933 // For parsing this time format, see ParseTime.
934 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
936 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
937 func appendTime(b []byte, t time.Time) []byte {
938 const days = "SunMonTueWedThuFriSat"
939 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
942 yy, mm, dd := t.Date()
943 hh, mn, ss := t.Clock()
944 day := days[3*t.Weekday():]
945 mon := months[3*(mm-1):]
948 day[0], day[1], day[2], ',', ' ',
949 byte('0'+dd/10), byte('0'+dd%10), ' ',
950 mon[0], mon[1], mon[2], ' ',
951 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
952 byte('0'+hh/10), byte('0'+hh%10), ':',
953 byte('0'+mn/10), byte('0'+mn%10), ':',
954 byte('0'+ss/10), byte('0'+ss%10), ' ',
958 var errTooLarge = errors.New("http: request too large")
960 // Read next request from connection.
961 func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
963 return nil, ErrHijacked
967 wholeReqDeadline time.Time // or zero if none
968 hdrDeadline time.Time // or zero if none
971 if d := c.server.readHeaderTimeout(); d > 0 {
972 hdrDeadline = t0.Add(d)
974 if d := c.server.ReadTimeout; d > 0 {
975 wholeReqDeadline = t0.Add(d)
977 c.rwc.SetReadDeadline(hdrDeadline)
978 if d := c.server.WriteTimeout; d > 0 {
980 c.rwc.SetWriteDeadline(time.Now().Add(d))
984 c.r.setReadLimit(c.server.initialReadLimitSize())
985 if c.lastMethod == "POST" {
986 // RFC 7230 section 3 tolerance for old buggy clients.
987 peek, _ := c.bufr.Peek(4) // ReadRequest will get err below
988 c.bufr.Discard(numLeadingCRorLF(peek))
990 req, err := readRequest(c.bufr)
992 if c.r.hitReadLimit() {
993 return nil, errTooLarge
998 if !http1ServerSupportsRequest(req) {
999 return nil, statusError{StatusHTTPVersionNotSupported, "unsupported protocol version"}
1002 c.lastMethod = req.Method
1003 c.r.setInfiniteReadLimit()
1005 hosts, haveHost := req.Header["Host"]
1006 isH2Upgrade := req.isH2Upgrade()
1007 if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
1008 return nil, badRequestError("missing required Host header")
1010 if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
1011 return nil, badRequestError("malformed Host header")
1013 for k, vv := range req.Header {
1014 if !httpguts.ValidHeaderFieldName(k) {
1015 return nil, badRequestError("invalid header name")
1017 for _, v := range vv {
1018 if !httpguts.ValidHeaderFieldValue(v) {
1019 return nil, badRequestError("invalid header value")
1023 delete(req.Header, "Host")
1025 ctx, cancelCtx := context.WithCancel(ctx)
1027 req.RemoteAddr = c.remoteAddr
1028 req.TLS = c.tlsState
1029 if body, ok := req.Body.(*body); ok {
1030 body.doEarlyClose = true
1033 // Adjust the read deadline if necessary.
1034 if !hdrDeadline.Equal(wholeReqDeadline) {
1035 c.rwc.SetReadDeadline(wholeReqDeadline)
1040 cancelCtx: cancelCtx,
1043 handlerHeader: make(Header),
1045 closeNotifyCh: make(chan bool, 1),
1047 // We populate these ahead of time so we're not
1048 // reading from req.Header after their Handler starts
1049 // and maybe mutates it (Issue 14940)
1050 wants10KeepAlive: req.wantsHttp10KeepAlive(),
1051 wantsClose: req.wantsClose(),
1054 w.closeAfterReply = true
1057 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
1061 // http1ServerSupportsRequest reports whether Go's HTTP/1.x server
1062 // supports the given request.
1063 func http1ServerSupportsRequest(req *Request) bool {
1064 if req.ProtoMajor == 1 {
1067 // Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
1068 // wire up their own HTTP/2 upgrades.
1069 if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
1070 req.Method == "PRI" && req.RequestURI == "*" {
1073 // Reject HTTP/0.x, and all other HTTP/2+ requests (which
1074 // aren't encoded in ASCII anyway).
1078 func (w *response) Header() Header {
1079 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
1080 // Accessing the header between logically writing it
1081 // and physically writing it means we need to allocate
1082 // a clone to snapshot the logically written state.
1083 w.cw.header = w.handlerHeader.Clone()
1085 w.calledHeader = true
1086 return w.handlerHeader
1089 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
1090 // consumed by a handler that the server will read from the client
1091 // in order to keep a connection alive. If there are more bytes than
1092 // this then the server to be paranoid instead sends a "Connection:
1095 // This number is approximately what a typical machine's TCP buffer
1096 // size is anyway. (if we have the bytes on the machine, we might as
1098 const maxPostHandlerReadBytes = 256 << 10
1100 func checkWriteHeaderCode(code int) {
1101 // Issue 22880: require valid WriteHeader status codes.
1102 // For now we only enforce that it's three digits.
1103 // In the future we might block things over 599 (600 and above aren't defined
1104 // at https://httpwg.org/specs/rfc7231.html#status.codes).
1105 // But for now any three digits.
1107 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
1108 // no equivalent bogus thing we can realistically send in HTTP/2,
1109 // so we'll consistently panic instead and help people find their bugs
1110 // early. (We can't return an error from WriteHeader even if we wanted to.)
1111 if code < 100 || code > 999 {
1112 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
1116 // relevantCaller searches the call stack for the first function outside of net/http.
1117 // The purpose of this function is to provide more helpful error messages.
1118 func relevantCaller() runtime.Frame {
1119 pc := make([]uintptr, 16)
1120 n := runtime.Callers(1, pc)
1121 frames := runtime.CallersFrames(pc[:n])
1122 var frame runtime.Frame
1124 frame, more := frames.Next()
1125 if !strings.HasPrefix(frame.Function, "net/http.") {
1135 func (w *response) WriteHeader(code int) {
1136 if w.conn.hijacked() {
1137 caller := relevantCaller()
1138 w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1142 caller := relevantCaller()
1143 w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1146 checkWriteHeaderCode(code)
1148 // Handle informational headers
1149 if code >= 100 && code <= 199 {
1150 // Prevent a potential race with an automatically-sent 100 Continue triggered by Request.Body.Read()
1151 if code == 100 && w.canWriteContinue.Load() {
1152 w.writeContinueMu.Lock()
1153 w.canWriteContinue.Store(false)
1154 w.writeContinueMu.Unlock()
1157 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1159 // Per RFC 8297 we must not clear the current header map
1160 w.handlerHeader.WriteSubset(w.conn.bufw, excludedHeadersNoBody)
1161 w.conn.bufw.Write(crlf)
1167 w.wroteHeader = true
1170 if w.calledHeader && w.cw.header == nil {
1171 w.cw.header = w.handlerHeader.Clone()
1174 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
1175 v, err := strconv.ParseInt(cl, 10, 64)
1176 if err == nil && v >= 0 {
1179 w.conn.server.logf("http: invalid Content-Length of %q", cl)
1180 w.handlerHeader.Del("Content-Length")
1185 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
1186 // This type is used to avoid extra allocations from cloning and/or populating
1187 // the response Header map and all its 1-element slices.
1188 type extraHeader struct {
1191 transferEncoding string
1192 date []byte // written if not nil
1193 contentLength []byte // written if not nil
1196 // Sorted the same as extraHeader.Write's loop.
1197 var extraHeaderKeys = [][]byte{
1198 []byte("Content-Type"),
1199 []byte("Connection"),
1200 []byte("Transfer-Encoding"),
1204 headerContentLength = []byte("Content-Length: ")
1205 headerDate = []byte("Date: ")
1208 // Write writes the headers described in h to w.
1210 // This method has a value receiver, despite the somewhat large size
1211 // of h, because it prevents an allocation. The escape analysis isn't
1212 // smart enough to realize this function doesn't mutate h.
1213 func (h extraHeader) Write(w *bufio.Writer) {
1219 if h.contentLength != nil {
1220 w.Write(headerContentLength)
1221 w.Write(h.contentLength)
1224 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
1226 w.Write(extraHeaderKeys[i])
1234 // writeHeader finalizes the header sent to the client and writes it
1235 // to cw.res.conn.bufw.
1237 // p is not written by writeHeader, but is the first chunk of the body
1238 // that will be written. It is sniffed for a Content-Type if none is
1239 // set explicitly. It's also used to set the Content-Length, if the
1240 // total body size was small and the handler has already finished
1242 func (cw *chunkWriter) writeHeader(p []byte) {
1246 cw.wroteHeader = true
1249 keepAlivesEnabled := w.conn.server.doKeepAlives()
1250 isHEAD := w.req.Method == "HEAD"
1252 // header is written out to w.conn.buf below. Depending on the
1253 // state of the handler, we either own the map or not. If we
1254 // don't own it, the exclude map is created lazily for
1255 // WriteSubset to remove headers. The setHeader struct holds
1256 // headers we need to add.
1258 owned := header != nil
1260 header = w.handlerHeader
1262 var excludeHeader map[string]bool
1263 delHeader := func(key string) {
1268 if _, ok := header[key]; !ok {
1271 if excludeHeader == nil {
1272 excludeHeader = make(map[string]bool)
1274 excludeHeader[key] = true
1276 var setHeader extraHeader
1278 // Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
1280 for k := range cw.header {
1281 if strings.HasPrefix(k, TrailerPrefix) {
1282 if excludeHeader == nil {
1283 excludeHeader = make(map[string]bool)
1285 excludeHeader[k] = true
1289 for _, v := range cw.header["Trailer"] {
1291 foreachHeaderElement(v, cw.res.declareTrailer)
1294 te := header.get("Transfer-Encoding")
1297 // If the handler is done but never sent a Content-Length
1298 // response header and this is our first (and last) write, set
1299 // it, even to zero. This helps HTTP/1.0 clients keep their
1300 // "keep-alive" connections alive.
1301 // Exceptions: 304/204/1xx responses never get Content-Length, and if
1302 // it was a HEAD request, we don't know the difference between
1303 // 0 actual bytes and 0 bytes because the handler noticed it
1304 // was a HEAD request and chose not to write anything. So for
1305 // HEAD, the handler should either write the Content-Length or
1306 // write non-zero bytes. If it's actually 0 bytes and the
1307 // handler never looked at the Request.Method, we just don't
1308 // send a Content-Length header.
1309 // Further, we don't send an automatic Content-Length if they
1310 // set a Transfer-Encoding, because they're generally incompatible.
1311 if w.handlerDone.Load() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
1312 w.contentLength = int64(len(p))
1313 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
1316 // If this was an HTTP/1.0 request with keep-alive and we sent a
1317 // Content-Length back, we can make this a keep-alive response ...
1318 if w.wants10KeepAlive && keepAlivesEnabled {
1319 sentLength := header.get("Content-Length") != ""
1320 if sentLength && header.get("Connection") == "keep-alive" {
1321 w.closeAfterReply = false
1325 // Check for an explicit (and valid) Content-Length header.
1326 hasCL := w.contentLength != -1
1328 if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
1329 _, connectionHeaderSet := header["Connection"]
1330 if !connectionHeaderSet {
1331 setHeader.connection = "keep-alive"
1333 } else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
1334 w.closeAfterReply = true
1337 if header.get("Connection") == "close" || !keepAlivesEnabled {
1338 w.closeAfterReply = true
1341 // If the client wanted a 100-continue but we never sent it to
1342 // them (or, more strictly: we never finished reading their
1343 // request body), don't reuse this connection because it's now
1344 // in an unknown state: we might be sending this response at
1345 // the same time the client is now sending its request body
1346 // after a timeout. (Some HTTP clients send Expect:
1347 // 100-continue but knowing that some servers don't support
1348 // it, the clients set a timer and send the body later anyway)
1349 // If we haven't seen EOF, we can't skip over the unread body
1350 // because we don't know if the next bytes on the wire will be
1351 // the body-following-the-timer or the subsequent request.
1353 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
1354 w.closeAfterReply = true
1357 // Per RFC 2616, we should consume the request body before
1358 // replying, if the handler hasn't already done so. But we
1359 // don't want to do an unbounded amount of reading here for
1360 // DoS reasons, so we only try up to a threshold.
1361 // TODO(bradfitz): where does RFC 2616 say that? See Issue 15527
1362 // about HTTP/1.x Handlers concurrently reading and writing, like
1363 // HTTP/2 handlers can do. Maybe this code should be relaxed?
1364 if w.req.ContentLength != 0 && !w.closeAfterReply {
1365 var discard, tooBig bool
1367 switch bdy := w.req.Body.(type) {
1368 case *expectContinueReader:
1369 if bdy.resp.wroteContinue {
1377 // Body was closed in handler with non-EOF error.
1378 w.closeAfterReply = true
1380 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
1391 _, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
1394 // There must be even more data left over.
1396 case ErrBodyReadAfterClose:
1397 // Body was already consumed and closed.
1399 // The remaining body was just consumed, close it.
1400 err = w.reqBody.Close()
1402 w.closeAfterReply = true
1405 // Some other kind of error occurred, like a read timeout, or
1406 // corrupt chunked encoding. In any case, whatever remains
1407 // on the wire must not be parsed as another HTTP request.
1408 w.closeAfterReply = true
1414 delHeader("Connection")
1415 setHeader.connection = "close"
1420 if bodyAllowedForStatus(code) {
1421 // If no content type, apply sniffing algorithm to body.
1422 _, haveType := header["Content-Type"]
1424 // If the Content-Encoding was set and is non-blank,
1425 // we shouldn't sniff the body. See Issue 31753.
1426 ce := header.Get("Content-Encoding")
1427 hasCE := len(ce) > 0
1428 if !hasCE && !haveType && !hasTE && len(p) > 0 {
1429 setHeader.contentType = DetectContentType(p)
1432 for _, k := range suppressedHeaders(code) {
1437 if !header.has("Date") {
1438 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
1441 if hasCL && hasTE && te != "identity" {
1442 // TODO: return an error if WriteHeader gets a return parameter
1443 // For now just ignore the Content-Length.
1444 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1445 te, w.contentLength)
1446 delHeader("Content-Length")
1450 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
1451 // Response has no body.
1452 delHeader("Transfer-Encoding")
1454 // Content-Length has been provided, so no chunking is to be done.
1455 delHeader("Transfer-Encoding")
1456 } else if w.req.ProtoAtLeast(1, 1) {
1457 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
1458 // content-length has been provided. The connection must be closed after the
1459 // reply is written, and no chunking is to be done. This is the setup
1460 // recommended in the Server-Sent Events candidate recommendation 11,
1462 if hasTE && te == "identity" {
1464 w.closeAfterReply = true
1465 delHeader("Transfer-Encoding")
1467 // HTTP/1.1 or greater: use chunked transfer encoding
1468 // to avoid closing the connection at EOF.
1470 setHeader.transferEncoding = "chunked"
1471 if hasTE && te == "chunked" {
1472 // We will send the chunked Transfer-Encoding header later.
1473 delHeader("Transfer-Encoding")
1477 // HTTP version < 1.1: cannot do chunked transfer
1478 // encoding and we don't know the Content-Length so
1479 // signal EOF by closing connection.
1480 w.closeAfterReply = true
1481 delHeader("Transfer-Encoding") // in case already set
1484 // Cannot use Content-Length with non-identity Transfer-Encoding.
1486 delHeader("Content-Length")
1488 if !w.req.ProtoAtLeast(1, 0) {
1492 // Only override the Connection header if it is not a successful
1493 // protocol switch response and if KeepAlives are not enabled.
1494 // See https://golang.org/issue/36381.
1495 delConnectionHeader := w.closeAfterReply &&
1496 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
1497 !isProtocolSwitchResponse(w.status, header)
1498 if delConnectionHeader {
1499 delHeader("Connection")
1500 if w.req.ProtoAtLeast(1, 1) {
1501 setHeader.connection = "close"
1505 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
1506 cw.header.WriteSubset(w.conn.bufw, excludeHeader)
1507 setHeader.Write(w.conn.bufw)
1508 w.conn.bufw.Write(crlf)
1511 // foreachHeaderElement splits v according to the "#rule" construction
1512 // in RFC 7230 section 7 and calls fn for each non-empty element.
1513 func foreachHeaderElement(v string, fn func(string)) {
1514 v = textproto.TrimString(v)
1518 if !strings.Contains(v, ",") {
1522 for _, f := range strings.Split(v, ",") {
1523 if f = textproto.TrimString(f); f != "" {
1529 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
1530 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
1531 // code is the response status code.
1532 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
1533 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
1535 bw.WriteString("HTTP/1.1 ")
1537 bw.WriteString("HTTP/1.0 ")
1539 if text := StatusText(code); text != "" {
1540 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
1542 bw.WriteString(text)
1543 bw.WriteString("\r\n")
1545 // don't worry about performance
1546 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
1550 // bodyAllowed reports whether a Write is allowed for this response type.
1551 // It's illegal to call this before the header has been flushed.
1552 func (w *response) bodyAllowed() bool {
1556 return bodyAllowedForStatus(w.status)
1559 // The Life Of A Write is like this:
1561 // Handler starts. No header has been sent. The handler can either
1562 // write a header, or just start writing. Writing before sending a header
1563 // sends an implicitly empty 200 OK header.
1565 // If the handler didn't declare a Content-Length up front, we either
1566 // go into chunking mode or, if the handler finishes running before
1567 // the chunking buffer size, we compute a Content-Length and send that
1568 // in the header instead.
1570 // Likewise, if the handler didn't set a Content-Type, we sniff that
1571 // from the initial chunk of output.
1573 // The Writers are wired together like:
1575 // 1. *response (the ResponseWriter) ->
1576 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes ->
1577 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
1578 // and which writes the chunk headers, if needed ->
1579 // 4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to ->
1580 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
1581 // and populates c.werr with it if so, but otherwise writes to ->
1582 // 6. the rwc, the net.Conn.
1584 // TODO(bradfitz): short-circuit some of the buffering when the
1585 // initial header contains both a Content-Type and Content-Length.
1586 // Also short-circuit in (1) when the header's been sent and not in
1587 // chunking mode, writing directly to (4) instead, if (2) has no
1588 // buffered data. More generally, we could short-circuit from (1) to
1589 // (3) even in chunking mode if the write size from (1) is over some
1590 // threshold and nothing is in (2). The answer might be mostly making
1591 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
1592 // with this instead.
1593 func (w *response) Write(data []byte) (n int, err error) {
1594 return w.write(len(data), data, "")
1597 func (w *response) WriteString(data string) (n int, err error) {
1598 return w.write(len(data), nil, data)
1601 // either dataB or dataS is non-zero.
1602 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
1603 if w.conn.hijacked() {
1605 caller := relevantCaller()
1606 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
1608 return 0, ErrHijacked
1611 if w.canWriteContinue.Load() {
1612 // Body reader wants to write 100 Continue but hasn't yet.
1613 // Tell it not to. The store must be done while holding the lock
1614 // because the lock makes sure that there is not an active write
1615 // this very moment.
1616 w.writeContinueMu.Lock()
1617 w.canWriteContinue.Store(false)
1618 w.writeContinueMu.Unlock()
1622 w.WriteHeader(StatusOK)
1627 if !w.bodyAllowed() {
1628 return 0, ErrBodyNotAllowed
1631 w.written += int64(lenData) // ignoring errors, for errorKludge
1632 if w.contentLength != -1 && w.written > w.contentLength {
1633 return 0, ErrContentLength
1636 return w.w.Write(dataB)
1638 return w.w.WriteString(dataS)
1642 func (w *response) finishRequest() {
1643 w.handlerDone.Store(true)
1646 w.WriteHeader(StatusOK)
1654 w.conn.r.abortPendingRead()
1656 // Close the body (regardless of w.closeAfterReply) so we can
1657 // re-use its bufio.Reader later safely.
1660 if w.req.MultipartForm != nil {
1661 w.req.MultipartForm.RemoveAll()
1665 // shouldReuseConnection reports whether the underlying TCP connection can be reused.
1666 // It must only be called after the handler is done executing.
1667 func (w *response) shouldReuseConnection() bool {
1668 if w.closeAfterReply {
1669 // The request or something set while executing the
1670 // handler indicated we shouldn't reuse this
1675 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1676 // Did not write enough. Avoid getting out of sync.
1680 // There was some error writing to the underlying connection
1681 // during the request, so don't re-use this conn.
1682 if w.conn.werr != nil {
1686 if w.closedRequestBodyEarly() {
1693 func (w *response) closedRequestBodyEarly() bool {
1694 body, ok := w.req.Body.(*body)
1695 return ok && body.didEarlyClose()
1698 func (w *response) Flush() {
1702 func (w *response) FlushError() error {
1704 w.WriteHeader(StatusOK)
1714 func (c *conn) finalFlush() {
1716 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1717 // reader for a future connection.
1718 putBufioReader(c.bufr)
1724 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1725 // writer for a future connection.
1726 putBufioWriter(c.bufw)
1731 // Close the connection.
1732 func (c *conn) close() {
1737 // rstAvoidanceDelay is the amount of time we sleep after closing the
1738 // write side of a TCP connection before closing the entire socket.
1739 // By sleeping, we increase the chances that the client sees our FIN
1740 // and processes its final data before they process the subsequent RST
1741 // from closing a connection with known unread data.
1742 // This RST seems to occur mostly on BSD systems. (And Windows?)
1743 // This timeout is somewhat arbitrary (~latency around the planet).
1744 const rstAvoidanceDelay = 500 * time.Millisecond
1746 type closeWriter interface {
1750 var _ closeWriter = (*net.TCPConn)(nil)
1752 // closeWriteAndWait flushes any outstanding data and sends a FIN packet (if
1753 // client is connected via TCP), signaling that we're done. We then
1754 // pause for a bit, hoping the client processes it before any
1757 // See https://golang.org/issue/3595
1758 func (c *conn) closeWriteAndWait() {
1760 if tcp, ok := c.rwc.(closeWriter); ok {
1763 time.Sleep(rstAvoidanceDelay)
1766 // validNextProto reports whether the proto is a valid ALPN protocol name.
1767 // Everything is valid except the empty string and built-in protocol types,
1768 // so that those can't be overridden with alternate implementations.
1769 func validNextProto(proto string) bool {
1771 case "", "http/1.1", "http/1.0":
1782 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
1786 srv.trackConn(c, true)
1787 case StateHijacked, StateClosed:
1788 srv.trackConn(c, false)
1790 if state > 0xff || state < 0 {
1791 panic("internal error")
1793 packedState := uint64(time.Now().Unix()<<8) | uint64(state)
1794 c.curState.Store(packedState)
1798 if hook := srv.ConnState; hook != nil {
1803 func (c *conn) getState() (state ConnState, unixSec int64) {
1804 packedState := c.curState.Load()
1805 return ConnState(packedState & 0xff), int64(packedState >> 8)
1808 // badRequestError is a literal string (used by in the server in HTML,
1809 // unescaped) to tell the user why their request was bad. It should
1810 // be plain text without user info or other embedded errors.
1811 func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
1813 // statusError is an error used to respond to a request with an HTTP status.
1814 // The text should be plain text without user info or other embedded errors.
1815 type statusError struct {
1820 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
1822 // ErrAbortHandler is a sentinel panic value to abort a handler.
1823 // While any panic from ServeHTTP aborts the response to the client,
1824 // panicking with ErrAbortHandler also suppresses logging of a stack
1825 // trace to the server's error log.
1826 var ErrAbortHandler = errors.New("net/http: abort Handler")
1828 // isCommonNetReadError reports whether err is a common error
1829 // encountered during reading a request off the network when the
1830 // client has gone away or had its read fail somehow. This is used to
1831 // determine which logs are interesting enough to log about.
1832 func isCommonNetReadError(err error) bool {
1836 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1839 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
1845 // Serve a new connection.
1846 func (c *conn) serve(ctx context.Context) {
1847 c.remoteAddr = c.rwc.RemoteAddr().String()
1848 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
1849 var inFlightResponse *response
1851 if err := recover(); err != nil && err != ErrAbortHandler {
1852 const size = 64 << 10
1853 buf := make([]byte, size)
1854 buf = buf[:runtime.Stack(buf, false)]
1855 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1857 if inFlightResponse != nil {
1858 inFlightResponse.cancelCtx()
1861 if inFlightResponse != nil {
1862 inFlightResponse.conn.r.abortPendingRead()
1863 inFlightResponse.reqBody.Close()
1866 c.setState(c.rwc, StateClosed, runHooks)
1870 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1871 tlsTO := c.server.tlsHandshakeTimeout()
1873 dl := time.Now().Add(tlsTO)
1874 c.rwc.SetReadDeadline(dl)
1875 c.rwc.SetWriteDeadline(dl)
1877 if err := tlsConn.HandshakeContext(ctx); err != nil {
1878 // If the handshake failed due to the client not speaking
1879 // TLS, assume they're speaking plaintext HTTP and write a
1880 // 400 response on the TLS conn's underlying net.Conn.
1881 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1882 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1886 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
1889 // Restore Conn-level deadlines.
1891 c.rwc.SetReadDeadline(time.Time{})
1892 c.rwc.SetWriteDeadline(time.Time{})
1894 c.tlsState = new(tls.ConnectionState)
1895 *c.tlsState = tlsConn.ConnectionState()
1896 if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
1897 if fn := c.server.TLSNextProto[proto]; fn != nil {
1898 h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
1899 // Mark freshly created HTTP/2 as active and prevent any server state hooks
1900 // from being run on these connections. This prevents closeIdleConns from
1901 // closing such connections. See issue https://golang.org/issue/39776.
1902 c.setState(c.rwc, StateActive, skipHooks)
1903 fn(c.server, tlsConn, h)
1909 // HTTP/1.x from here on.
1911 ctx, cancelCtx := context.WithCancel(ctx)
1912 c.cancelCtx = cancelCtx
1915 c.r = &connReader{conn: c}
1916 c.bufr = newBufioReader(c.r)
1917 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
1920 w, err := c.readRequest(ctx)
1921 if c.r.remain != c.server.initialReadLimitSize() {
1922 // If we read any bytes off the wire, we're active.
1923 c.setState(c.rwc, StateActive, runHooks)
1926 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1929 case err == errTooLarge:
1930 // Their HTTP client may or may not be
1931 // able to read this if we're
1932 // responding to them and hanging up
1933 // while they're still writing their
1934 // request. Undefined behavior.
1935 const publicErr = "431 Request Header Fields Too Large"
1936 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1937 c.closeWriteAndWait()
1940 case isUnsupportedTEError(err):
1941 // Respond as per RFC 7230 Section 3.3.1 which says,
1942 // A server that receives a request message with a
1943 // transfer coding it does not understand SHOULD
1944 // respond with 501 (Unimplemented).
1945 code := StatusNotImplemented
1947 // We purposefully aren't echoing back the transfer-encoding's value,
1948 // so as to mitigate the risk of cross side scripting by an attacker.
1949 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
1952 case isCommonNetReadError(err):
1953 return // don't reply
1956 if v, ok := err.(statusError); ok {
1957 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)
1960 publicErr := "400 Bad Request"
1961 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
1966 // Expect 100 Continue support
1968 if req.expectsContinue() {
1969 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
1970 // Wrap the Body reader with one that replies on the connection
1971 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
1972 w.canWriteContinue.Store(true)
1974 } else if req.Header.get("Expect") != "" {
1975 w.sendExpectationFailed()
1981 if requestBodyRemains(req.Body) {
1982 registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
1984 w.conn.r.startBackgroundRead()
1987 // HTTP cannot have multiple simultaneous active requests.[*]
1988 // Until the server replies to this request, it can't read another,
1989 // so we might as well run the handler in this goroutine.
1990 // [*] Not strictly true: HTTP pipelining. We could let them all process
1991 // in parallel even if their responses need to be serialized.
1992 // But we're not going to implement HTTP pipelining because it
1993 // was never deployed in the wild and the answer is HTTP/2.
1994 inFlightResponse = w
1995 serverHandler{c.server}.ServeHTTP(w, w.req)
1996 inFlightResponse = nil
2002 c.rwc.SetWriteDeadline(time.Time{})
2003 if !w.shouldReuseConnection() {
2004 if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
2005 c.closeWriteAndWait()
2009 c.setState(c.rwc, StateIdle, runHooks)
2012 if !w.conn.server.doKeepAlives() {
2013 // We're in shutdown mode. We might've replied
2014 // to the user without "Connection: close" and
2015 // they might think they can send another
2016 // request, but such is life with HTTP/1.1.
2020 if d := c.server.idleTimeout(); d != 0 {
2021 c.rwc.SetReadDeadline(time.Now().Add(d))
2023 c.rwc.SetReadDeadline(time.Time{})
2026 // Wait for the connection to become readable again before trying to
2027 // read the next request. This prevents a ReadHeaderTimeout or
2028 // ReadTimeout from starting until the first bytes of the next request
2029 // have been received.
2030 if _, err := c.bufr.Peek(4); err != nil {
2034 c.rwc.SetReadDeadline(time.Time{})
2038 func (w *response) sendExpectationFailed() {
2039 // TODO(bradfitz): let ServeHTTP handlers handle
2040 // requests with non-standard expectation[s]? Seems
2041 // theoretical at best, and doesn't fit into the
2042 // current ServeHTTP model anyway. We'd need to
2043 // make the ResponseWriter an optional
2044 // "ExpectReplier" interface or something.
2046 // For now we'll just obey RFC 7231 5.1.1 which says
2047 // "A server that receives an Expect field-value other
2048 // than 100-continue MAY respond with a 417 (Expectation
2049 // Failed) status code to indicate that the unexpected
2050 // expectation cannot be met."
2051 w.Header().Set("Connection", "close")
2052 w.WriteHeader(StatusExpectationFailed)
2056 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
2058 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
2059 if w.handlerDone.Load() {
2060 panic("net/http: Hijack called after ServeHTTP finished")
2070 // Release the bufioWriter that writes to the chunk writer, it is not
2071 // used after a connection has been hijacked.
2072 rwc, buf, err = c.hijackLocked()
2077 return rwc, buf, err
2080 func (w *response) CloseNotify() <-chan bool {
2081 if w.handlerDone.Load() {
2082 panic("net/http: CloseNotify called after ServeHTTP finished")
2084 return w.closeNotifyCh
2087 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
2088 switch v := rc.(type) {
2089 case *expectContinueReader:
2090 registerOnHitEOF(v.readCloser, fn)
2092 v.registerOnHitEOF(fn)
2094 panic("unexpected type " + fmt.Sprintf("%T", rc))
2098 // requestBodyRemains reports whether future calls to Read
2099 // on rc might yield more data.
2100 func requestBodyRemains(rc io.ReadCloser) bool {
2104 switch v := rc.(type) {
2105 case *expectContinueReader:
2106 return requestBodyRemains(v.readCloser)
2108 return v.bodyRemains()
2110 panic("unexpected type " + fmt.Sprintf("%T", rc))
2114 // The HandlerFunc type is an adapter to allow the use of
2115 // ordinary functions as HTTP handlers. If f is a function
2116 // with the appropriate signature, HandlerFunc(f) is a
2117 // Handler that calls f.
2118 type HandlerFunc func(ResponseWriter, *Request)
2120 // ServeHTTP calls f(w, r).
2121 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
2127 // Error replies to the request with the specified error message and HTTP code.
2128 // It does not otherwise end the request; the caller should ensure no further
2129 // writes are done to w.
2130 // The error message should be plain text.
2131 func Error(w ResponseWriter, error string, code int) {
2132 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2133 w.Header().Set("X-Content-Type-Options", "nosniff")
2135 fmt.Fprintln(w, error)
2138 // NotFound replies to the request with an HTTP 404 not found error.
2139 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
2141 // NotFoundHandler returns a simple request handler
2142 // that replies to each request with a “404 page not found” reply.
2143 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
2145 // StripPrefix returns a handler that serves HTTP requests by removing the
2146 // given prefix from the request URL's Path (and RawPath if set) and invoking
2147 // the handler h. StripPrefix handles a request for a path that doesn't begin
2148 // with prefix by replying with an HTTP 404 not found error. The prefix must
2149 // match exactly: if the prefix in the request contains escaped characters
2150 // the reply is also an HTTP 404 not found error.
2151 func StripPrefix(prefix string, h Handler) Handler {
2155 return HandlerFunc(func(w ResponseWriter, r *Request) {
2156 p := strings.TrimPrefix(r.URL.Path, prefix)
2157 rp := strings.TrimPrefix(r.URL.RawPath, prefix)
2158 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
2161 r2.URL = new(url.URL)
2172 // Redirect replies to the request with a redirect to url,
2173 // which may be a path relative to the request path.
2175 // The provided code should be in the 3xx range and is usually
2176 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2178 // If the Content-Type header has not been set, Redirect sets it
2179 // to "text/html; charset=utf-8" and writes a small HTML body.
2180 // Setting the Content-Type header to any value, including nil,
2181 // disables that behavior.
2182 func Redirect(w ResponseWriter, r *Request, url string, code int) {
2183 if u, err := urlpkg.Parse(url); err == nil {
2184 // If url was relative, make its path absolute by
2185 // combining with request path.
2186 // The client would probably do this for us,
2187 // but doing it ourselves is more reliable.
2188 // See RFC 7231, section 7.1.2
2189 if u.Scheme == "" && u.Host == "" {
2190 oldpath := r.URL.Path
2191 if oldpath == "" { // should not happen, but avoid a crash if it does
2195 // no leading http://server
2196 if url == "" || url[0] != '/' {
2197 // make relative path absolute
2198 olddir, _ := path.Split(oldpath)
2203 if i := strings.Index(url, "?"); i != -1 {
2204 url, query = url[:i], url[i:]
2207 // clean up but preserve trailing slash
2208 trailing := strings.HasSuffix(url, "/")
2209 url = path.Clean(url)
2210 if trailing && !strings.HasSuffix(url, "/") {
2219 // RFC 7231 notes that a short HTML body is usually included in
2220 // the response because older user agents may not understand 301/307.
2221 // Do it only if the request didn't already have a Content-Type header.
2222 _, hadCT := h["Content-Type"]
2224 h.Set("Location", hexEscapeNonASCII(url))
2225 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
2226 h.Set("Content-Type", "text/html; charset=utf-8")
2230 // Shouldn't send the body for POST or HEAD; that leaves GET.
2231 if !hadCT && r.Method == "GET" {
2232 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
2233 fmt.Fprintln(w, body)
2237 var htmlReplacer = strings.NewReplacer(
2241 // """ is shorter than """.
2243 // "'" is shorter than "'" and apos was not in HTML until HTML5.
2247 func htmlEscape(s string) string {
2248 return htmlReplacer.Replace(s)
2251 // Redirect to a fixed URL
2252 type redirectHandler struct {
2257 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
2258 Redirect(w, r, rh.url, rh.code)
2261 // RedirectHandler returns a request handler that redirects
2262 // each request it receives to the given url using the given
2265 // The provided code should be in the 3xx range and is usually
2266 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2267 func RedirectHandler(url string, code int) Handler {
2268 return &redirectHandler{url, code}
2271 // ServeMux is an HTTP request multiplexer.
2272 // It matches the URL of each incoming request against a list of registered
2273 // patterns and calls the handler for the pattern that
2274 // most closely matches the URL.
2276 // Patterns name fixed, rooted paths, like "/favicon.ico",
2277 // or rooted subtrees, like "/images/" (note the trailing slash).
2278 // Longer patterns take precedence over shorter ones, so that
2279 // if there are handlers registered for both "/images/"
2280 // and "/images/thumbnails/", the latter handler will be
2281 // called for paths beginning with "/images/thumbnails/" and the
2282 // former will receive requests for any other paths in the
2283 // "/images/" subtree.
2285 // Note that since a pattern ending in a slash names a rooted subtree,
2286 // the pattern "/" matches all paths not matched by other registered
2287 // patterns, not just the URL with Path == "/".
2289 // If a subtree has been registered and a request is received naming the
2290 // subtree root without its trailing slash, ServeMux redirects that
2291 // request to the subtree root (adding the trailing slash). This behavior can
2292 // be overridden with a separate registration for the path without
2293 // the trailing slash. For example, registering "/images/" causes ServeMux
2294 // to redirect a request for "/images" to "/images/", unless "/images" has
2295 // been registered separately.
2297 // Patterns may optionally begin with a host name, restricting matches to
2298 // URLs on that host only. Host-specific patterns take precedence over
2299 // general patterns, so that a handler might register for the two patterns
2300 // "/codesearch" and "codesearch.google.com/" without also taking over
2301 // requests for "http://www.google.com/".
2303 // ServeMux also takes care of sanitizing the URL request path and the Host
2304 // header, stripping the port number and redirecting any request containing . or
2305 // .. elements or repeated slashes to an equivalent, cleaner URL.
2306 type ServeMux struct {
2308 m map[string]muxEntry
2309 es []muxEntry // slice of entries sorted from longest to shortest.
2310 hosts bool // whether any patterns contain hostnames
2313 type muxEntry struct {
2318 // NewServeMux allocates and returns a new ServeMux.
2319 func NewServeMux() *ServeMux { return new(ServeMux) }
2321 // DefaultServeMux is the default ServeMux used by Serve.
2322 var DefaultServeMux = &defaultServeMux
2324 var defaultServeMux ServeMux
2326 // cleanPath returns the canonical path for p, eliminating . and .. elements.
2327 func cleanPath(p string) string {
2335 // path.Clean removes trailing slash except for root;
2336 // put the trailing slash back if necessary.
2337 if p[len(p)-1] == '/' && np != "/" {
2338 // Fast path for common case of p being the string we want:
2339 if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2348 // stripHostPort returns h without any trailing ":<port>".
2349 func stripHostPort(h string) string {
2350 // If no port on host, return unchanged
2351 if !strings.Contains(h, ":") {
2354 host, _, err := net.SplitHostPort(h)
2356 return h // on error, return unchanged
2361 // Find a handler on a handler map given a path string.
2362 // Most-specific (longest) pattern wins.
2363 func (mux *ServeMux) match(path string) (h Handler, pattern string) {
2364 // Check for exact match first.
2365 v, ok := mux.m[path]
2367 return v.h, v.pattern
2370 // Check for longest valid match. mux.es contains all patterns
2371 // that end in / sorted from longest to shortest.
2372 for _, e := range mux.es {
2373 if strings.HasPrefix(path, e.pattern) {
2374 return e.h, e.pattern
2380 // redirectToPathSlash determines if the given path needs appending "/" to it.
2381 // This occurs when a handler for path + "/" was already registered, but
2382 // not for path itself. If the path needs appending to, it creates a new
2383 // URL, setting the path to u.Path + "/" and returning true to indicate so.
2384 func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool) {
2386 shouldRedirect := mux.shouldRedirectRLocked(host, path)
2388 if !shouldRedirect {
2392 u = &url.URL{Path: path, RawQuery: u.RawQuery}
2396 // shouldRedirectRLocked reports whether the given path and host should be redirected to
2397 // path+"/". This should happen if a handler is registered for path+"/" but
2398 // not path -- see comments at ServeMux.
2399 func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool {
2400 p := []string{path, host + path}
2402 for _, c := range p {
2403 if _, exist := mux.m[c]; exist {
2412 for _, c := range p {
2413 if _, exist := mux.m[c+"/"]; exist {
2414 return path[n-1] != '/'
2421 // Handler returns the handler to use for the given request,
2422 // consulting r.Method, r.Host, and r.URL.Path. It always returns
2423 // a non-nil handler. If the path is not in its canonical form, the
2424 // handler will be an internally-generated handler that redirects
2425 // to the canonical path. If the host contains a port, it is ignored
2426 // when matching handlers.
2428 // The path and host are used unchanged for CONNECT requests.
2430 // Handler also returns the registered pattern that matches the
2431 // request or, in the case of internally-generated redirects,
2432 // the pattern that will match after following the redirect.
2434 // If there is no registered handler that applies to the request,
2435 // Handler returns a “page not found” handler and an empty pattern.
2436 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
2438 // CONNECT requests are not canonicalized.
2439 if r.Method == "CONNECT" {
2440 // If r.URL.Path is /tree and its handler is not registered,
2441 // the /tree -> /tree/ redirect applies to CONNECT requests
2442 // but the path canonicalization does not.
2443 if u, ok := mux.redirectToPathSlash(r.URL.Host, r.URL.Path, r.URL); ok {
2444 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
2447 return mux.handler(r.Host, r.URL.Path)
2450 // All other requests have any port stripped and path cleaned
2451 // before passing to mux.handler.
2452 host := stripHostPort(r.Host)
2453 path := cleanPath(r.URL.Path)
2455 // If the given path is /tree and its handler is not registered,
2456 // redirect for /tree/.
2457 if u, ok := mux.redirectToPathSlash(host, path, r.URL); ok {
2458 return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
2461 if path != r.URL.Path {
2462 _, pattern = mux.handler(host, path)
2463 u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
2464 return RedirectHandler(u.String(), StatusMovedPermanently), pattern
2467 return mux.handler(host, r.URL.Path)
2470 // handler is the main implementation of Handler.
2471 // The path is known to be in canonical form, except for CONNECT methods.
2472 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
2474 defer mux.mu.RUnlock()
2476 // Host-specific pattern takes precedence over generic ones
2478 h, pattern = mux.match(host + path)
2481 h, pattern = mux.match(path)
2484 h, pattern = NotFoundHandler(), ""
2489 // ServeHTTP dispatches the request to the handler whose
2490 // pattern most closely matches the request URL.
2491 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
2492 if r.RequestURI == "*" {
2493 if r.ProtoAtLeast(1, 1) {
2494 w.Header().Set("Connection", "close")
2496 w.WriteHeader(StatusBadRequest)
2499 h, _ := mux.Handler(r)
2503 // Handle registers the handler for the given pattern.
2504 // If a handler already exists for pattern, Handle panics.
2505 func (mux *ServeMux) Handle(pattern string, handler Handler) {
2507 defer mux.mu.Unlock()
2510 panic("http: invalid pattern")
2513 panic("http: nil handler")
2515 if _, exist := mux.m[pattern]; exist {
2516 panic("http: multiple registrations for " + pattern)
2520 mux.m = make(map[string]muxEntry)
2522 e := muxEntry{h: handler, pattern: pattern}
2524 if pattern[len(pattern)-1] == '/' {
2525 mux.es = appendSorted(mux.es, e)
2528 if pattern[0] != '/' {
2533 func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
2535 i := sort.Search(n, func(i int) bool {
2536 return len(es[i].pattern) < len(e.pattern)
2539 return append(es, e)
2541 // we now know that i points at where we want to insert
2542 es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
2543 copy(es[i+1:], es[i:]) // Move shorter entries down
2548 // HandleFunc registers the handler function for the given pattern.
2549 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2551 panic("http: nil handler")
2553 mux.Handle(pattern, HandlerFunc(handler))
2556 // Handle registers the handler for the given pattern
2557 // in the DefaultServeMux.
2558 // The documentation for ServeMux explains how patterns are matched.
2559 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
2561 // HandleFunc registers the handler function for the given pattern
2562 // in the DefaultServeMux.
2563 // The documentation for ServeMux explains how patterns are matched.
2564 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
2565 DefaultServeMux.HandleFunc(pattern, handler)
2568 // Serve accepts incoming HTTP connections on the listener l,
2569 // creating a new service goroutine for each. The service goroutines
2570 // read requests and then call handler to reply to them.
2572 // The handler is typically nil, in which case the DefaultServeMux is used.
2574 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
2575 // connections and they were configured with "h2" in the TLS
2576 // Config.NextProtos.
2578 // Serve always returns a non-nil error.
2579 func Serve(l net.Listener, handler Handler) error {
2580 srv := &Server{Handler: handler}
2584 // ServeTLS accepts incoming HTTPS connections on the listener l,
2585 // creating a new service goroutine for each. The service goroutines
2586 // read requests and then call handler to reply to them.
2588 // The handler is typically nil, in which case the DefaultServeMux is used.
2590 // Additionally, files containing a certificate and matching private key
2591 // for the server must be provided. If the certificate is signed by a
2592 // certificate authority, the certFile should be the concatenation
2593 // of the server's certificate, any intermediates, and the CA's certificate.
2595 // ServeTLS always returns a non-nil error.
2596 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
2597 srv := &Server{Handler: handler}
2598 return srv.ServeTLS(l, certFile, keyFile)
2601 // A Server defines parameters for running an HTTP server.
2602 // The zero value for Server is a valid configuration.
2603 type Server struct {
2604 // Addr optionally specifies the TCP address for the server to listen on,
2605 // in the form "host:port". If empty, ":http" (port 80) is used.
2606 // The service names are defined in RFC 6335 and assigned by IANA.
2607 // See net.Dial for details of the address format.
2610 Handler Handler // handler to invoke, http.DefaultServeMux if nil
2612 // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
2613 // otherwise responds with 200 OK and Content-Length: 0.
2614 DisableGeneralOptionsHandler bool
2616 // TLSConfig optionally provides a TLS configuration for use
2617 // by ServeTLS and ListenAndServeTLS. Note that this value is
2618 // cloned by ServeTLS and ListenAndServeTLS, so it's not
2619 // possible to modify the configuration with methods like
2620 // tls.Config.SetSessionTicketKeys. To use
2621 // SetSessionTicketKeys, use Server.Serve with a TLS Listener
2623 TLSConfig *tls.Config
2625 // ReadTimeout is the maximum duration for reading the entire
2626 // request, including the body. A zero or negative value means
2627 // there will be no timeout.
2629 // Because ReadTimeout does not let Handlers make per-request
2630 // decisions on each request body's acceptable deadline or
2631 // upload rate, most users will prefer to use
2632 // ReadHeaderTimeout. It is valid to use them both.
2633 ReadTimeout time.Duration
2635 // ReadHeaderTimeout is the amount of time allowed to read
2636 // request headers. The connection's read deadline is reset
2637 // after reading the headers and the Handler can decide what
2638 // is considered too slow for the body. If ReadHeaderTimeout
2639 // is zero, the value of ReadTimeout is used. If both are
2640 // zero, there is no timeout.
2641 ReadHeaderTimeout time.Duration
2643 // WriteTimeout is the maximum duration before timing out
2644 // writes of the response. It is reset whenever a new
2645 // request's header is read. Like ReadTimeout, it does not
2646 // let Handlers make decisions on a per-request basis.
2647 // A zero or negative value means there will be no timeout.
2648 WriteTimeout time.Duration
2650 // IdleTimeout is the maximum amount of time to wait for the
2651 // next request when keep-alives are enabled. If IdleTimeout
2652 // is zero, the value of ReadTimeout is used. If both are
2653 // zero, there is no timeout.
2654 IdleTimeout time.Duration
2656 // MaxHeaderBytes controls the maximum number of bytes the
2657 // server will read parsing the request header's keys and
2658 // values, including the request line. It does not limit the
2659 // size of the request body.
2660 // If zero, DefaultMaxHeaderBytes is used.
2663 // TLSNextProto optionally specifies a function to take over
2664 // ownership of the provided TLS connection when an ALPN
2665 // protocol upgrade has occurred. The map key is the protocol
2666 // name negotiated. The Handler argument should be used to
2667 // handle HTTP requests and will initialize the Request's TLS
2668 // and RemoteAddr if not already set. The connection is
2669 // automatically closed when the function returns.
2670 // If TLSNextProto is not nil, HTTP/2 support is not enabled
2672 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
2674 // ConnState specifies an optional callback function that is
2675 // called when a client connection changes state. See the
2676 // ConnState type and associated constants for details.
2677 ConnState func(net.Conn, ConnState)
2679 // ErrorLog specifies an optional logger for errors accepting
2680 // connections, unexpected behavior from handlers, and
2681 // underlying FileSystem errors.
2682 // If nil, logging is done via the log package's standard logger.
2683 ErrorLog *log.Logger
2685 // BaseContext optionally specifies a function that returns
2686 // the base context for incoming requests on this server.
2687 // The provided Listener is the specific Listener that's
2688 // about to start accepting requests.
2689 // If BaseContext is nil, the default is context.Background().
2690 // If non-nil, it must return a non-nil context.
2691 BaseContext func(net.Listener) context.Context
2693 // ConnContext optionally specifies a function that modifies
2694 // the context used for a new connection c. The provided ctx
2695 // is derived from the base context and has a ServerContextKey
2697 ConnContext func(ctx context.Context, c net.Conn) context.Context
2699 inShutdown atomic.Bool // true when server is in shutdown
2701 disableKeepAlives atomic.Bool
2702 nextProtoOnce sync.Once // guards setupHTTP2_* init
2703 nextProtoErr error // result of http2.ConfigureServer if used
2706 listeners map[*net.Listener]struct{}
2707 activeConn map[*conn]struct{}
2710 listenerGroup sync.WaitGroup
2713 // Close immediately closes all active net.Listeners and any
2714 // connections in state StateNew, StateActive, or StateIdle. For a
2715 // graceful shutdown, use Shutdown.
2717 // Close does not attempt to close (and does not even know about)
2718 // any hijacked connections, such as WebSockets.
2720 // Close returns any error returned from closing the Server's
2721 // underlying Listener(s).
2722 func (srv *Server) Close() error {
2723 srv.inShutdown.Store(true)
2725 defer srv.mu.Unlock()
2726 err := srv.closeListenersLocked()
2728 // Unlock srv.mu while waiting for listenerGroup.
2729 // The group Add and Done calls are made with srv.mu held,
2730 // to avoid adding a new listener in the window between
2731 // us setting inShutdown above and waiting here.
2733 srv.listenerGroup.Wait()
2736 for c := range srv.activeConn {
2738 delete(srv.activeConn, c)
2743 // shutdownPollIntervalMax is the max polling interval when checking
2744 // quiescence during Server.Shutdown. Polling starts with a small
2745 // interval and backs off to the max.
2746 // Ideally we could find a solution that doesn't involve polling,
2747 // but which also doesn't have a high runtime cost (and doesn't
2748 // involve any contentious mutexes), but that is left as an
2749 // exercise for the reader.
2750 const shutdownPollIntervalMax = 500 * time.Millisecond
2752 // Shutdown gracefully shuts down the server without interrupting any
2753 // active connections. Shutdown works by first closing all open
2754 // listeners, then closing all idle connections, and then waiting
2755 // indefinitely for connections to return to idle and then shut down.
2756 // If the provided context expires before the shutdown is complete,
2757 // Shutdown returns the context's error, otherwise it returns any
2758 // error returned from closing the Server's underlying Listener(s).
2760 // When Shutdown is called, Serve, ListenAndServe, and
2761 // ListenAndServeTLS immediately return ErrServerClosed. Make sure the
2762 // program doesn't exit and waits instead for Shutdown to return.
2764 // Shutdown does not attempt to close nor wait for hijacked
2765 // connections such as WebSockets. The caller of Shutdown should
2766 // separately notify such long-lived connections of shutdown and wait
2767 // for them to close, if desired. See RegisterOnShutdown for a way to
2768 // register shutdown notification functions.
2770 // Once Shutdown has been called on a server, it may not be reused;
2771 // future calls to methods such as Serve will return ErrServerClosed.
2772 func (srv *Server) Shutdown(ctx context.Context) error {
2773 srv.inShutdown.Store(true)
2776 lnerr := srv.closeListenersLocked()
2777 for _, f := range srv.onShutdown {
2781 srv.listenerGroup.Wait()
2783 pollIntervalBase := time.Millisecond
2784 nextPollInterval := func() time.Duration {
2786 interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
2787 // Double and clamp for next time.
2788 pollIntervalBase *= 2
2789 if pollIntervalBase > shutdownPollIntervalMax {
2790 pollIntervalBase = shutdownPollIntervalMax
2795 timer := time.NewTimer(nextPollInterval())
2798 if srv.closeIdleConns() {
2805 timer.Reset(nextPollInterval())
2810 // RegisterOnShutdown registers a function to call on Shutdown.
2811 // This can be used to gracefully shutdown connections that have
2812 // undergone ALPN protocol upgrade or that have been hijacked.
2813 // This function should start protocol-specific graceful shutdown,
2814 // but should not wait for shutdown to complete.
2815 func (srv *Server) RegisterOnShutdown(f func()) {
2817 srv.onShutdown = append(srv.onShutdown, f)
2821 // closeIdleConns closes all idle connections and reports whether the
2822 // server is quiescent.
2823 func (s *Server) closeIdleConns() bool {
2827 for c := range s.activeConn {
2828 st, unixSec := c.getState()
2829 // Issue 22682: treat StateNew connections as if
2830 // they're idle if we haven't read the first request's
2831 // header in over 5 seconds.
2832 if st == StateNew && unixSec < time.Now().Unix()-5 {
2835 if st != StateIdle || unixSec == 0 {
2836 // Assume unixSec == 0 means it's a very new
2837 // connection, without state set yet.
2842 delete(s.activeConn, c)
2847 func (s *Server) closeListenersLocked() error {
2849 for ln := range s.listeners {
2850 if cerr := (*ln).Close(); cerr != nil && err == nil {
2857 // A ConnState represents the state of a client connection to a server.
2858 // It's used by the optional Server.ConnState hook.
2862 // StateNew represents a new connection that is expected to
2863 // send a request immediately. Connections begin at this
2864 // state and then transition to either StateActive or
2866 StateNew ConnState = iota
2868 // StateActive represents a connection that has read 1 or more
2869 // bytes of a request. The Server.ConnState hook for
2870 // StateActive fires before the request has entered a handler
2871 // and doesn't fire again until the request has been
2872 // handled. After the request is handled, the state
2873 // transitions to StateClosed, StateHijacked, or StateIdle.
2874 // For HTTP/2, StateActive fires on the transition from zero
2875 // to one active request, and only transitions away once all
2876 // active requests are complete. That means that ConnState
2877 // cannot be used to do per-request work; ConnState only notes
2878 // the overall state of the connection.
2881 // StateIdle represents a connection that has finished
2882 // handling a request and is in the keep-alive state, waiting
2883 // for a new request. Connections transition from StateIdle
2884 // to either StateActive or StateClosed.
2887 // StateHijacked represents a hijacked connection.
2888 // This is a terminal state. It does not transition to StateClosed.
2891 // StateClosed represents a closed connection.
2892 // This is a terminal state. Hijacked connections do not
2893 // transition to StateClosed.
2897 var stateName = map[ConnState]string{
2899 StateActive: "active",
2901 StateHijacked: "hijacked",
2902 StateClosed: "closed",
2905 func (c ConnState) String() string {
2909 // serverHandler delegates to either the server's Handler or
2910 // DefaultServeMux and also handles "OPTIONS *" requests.
2911 type serverHandler struct {
2915 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
2916 handler := sh.srv.Handler
2918 handler = DefaultServeMux
2920 if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
2921 handler = globalOptionsHandler{}
2924 handler.ServeHTTP(rw, req)
2927 // AllowQuerySemicolons returns a handler that serves requests by converting any
2928 // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
2930 // This restores the pre-Go 1.17 behavior of splitting query parameters on both
2931 // semicolons and ampersands. (See golang.org/issue/25192). Note that this
2932 // behavior doesn't match that of many proxies, and the mismatch can lead to
2935 // AllowQuerySemicolons should be invoked before Request.ParseForm is called.
2936 func AllowQuerySemicolons(h Handler) Handler {
2937 return HandlerFunc(func(w ResponseWriter, r *Request) {
2938 if strings.Contains(r.URL.RawQuery, ";") {
2941 r2.URL = new(url.URL)
2943 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
2951 // ListenAndServe listens on the TCP network address srv.Addr and then
2952 // calls Serve to handle requests on incoming connections.
2953 // Accepted connections are configured to enable TCP keep-alives.
2955 // If srv.Addr is blank, ":http" is used.
2957 // ListenAndServe always returns a non-nil error. After Shutdown or Close,
2958 // the returned error is ErrServerClosed.
2959 func (srv *Server) ListenAndServe() error {
2960 if srv.shuttingDown() {
2961 return ErrServerClosed
2967 ln, err := net.Listen("tcp", addr)
2971 return srv.Serve(ln)
2974 var testHookServerServe func(*Server, net.Listener) // used if non-nil
2976 // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
2977 // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
2978 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
2979 if srv.TLSConfig == nil {
2980 // Compatibility with Go 1.6:
2981 // If there's no TLSConfig, it's possible that the user just
2982 // didn't set it on the http.Server, but did pass it to
2983 // tls.NewListener and passed that listener to Serve.
2984 // So we should configure HTTP/2 (to set up srv.TLSNextProto)
2985 // in case the listener returns an "h2" *tls.Conn.
2988 // The user specified a TLSConfig on their http.Server.
2989 // In this, case, only configure HTTP/2 if their tls.Config
2990 // explicitly mentions "h2". Otherwise http2.ConfigureServer
2991 // would modify the tls.Config to add it, but they probably already
2992 // passed this tls.Config to tls.NewListener. And if they did,
2993 // it's too late anyway to fix it. It would only be potentially racy.
2995 return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
2998 // ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
2999 // and ListenAndServeTLS methods after a call to Shutdown or Close.
3000 var ErrServerClosed = errors.New("http: Server closed")
3002 // Serve accepts incoming connections on the Listener l, creating a
3003 // new service goroutine for each. The service goroutines read requests and
3004 // then call srv.Handler to reply to them.
3006 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
3007 // connections and they were configured with "h2" in the TLS
3008 // Config.NextProtos.
3010 // Serve always returns a non-nil error and closes l.
3011 // After Shutdown or Close, the returned error is ErrServerClosed.
3012 func (srv *Server) Serve(l net.Listener) error {
3013 if fn := testHookServerServe; fn != nil {
3014 fn(srv, l) // call hook with unwrapped listener
3018 l = &onceCloseListener{Listener: l}
3021 if err := srv.setupHTTP2_Serve(); err != nil {
3025 if !srv.trackListener(&l, true) {
3026 return ErrServerClosed
3028 defer srv.trackListener(&l, false)
3030 baseCtx := context.Background()
3031 if srv.BaseContext != nil {
3032 baseCtx = srv.BaseContext(origListener)
3034 panic("BaseContext returned a nil context")
3038 var tempDelay time.Duration // how long to sleep on accept failure
3040 ctx := context.WithValue(baseCtx, ServerContextKey, srv)
3042 rw, err := l.Accept()
3044 if srv.shuttingDown() {
3045 return ErrServerClosed
3047 if ne, ok := err.(net.Error); ok && ne.Temporary() {
3049 tempDelay = 5 * time.Millisecond
3053 if max := 1 * time.Second; tempDelay > max {
3056 srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
3057 time.Sleep(tempDelay)
3063 if cc := srv.ConnContext; cc != nil {
3064 connCtx = cc(connCtx, rw)
3066 panic("ConnContext returned nil")
3070 c := srv.newConn(rw)
3071 c.setState(c.rwc, StateNew, runHooks) // before Serve can return
3076 // ServeTLS accepts incoming connections on the Listener l, creating a
3077 // new service goroutine for each. The service goroutines perform TLS
3078 // setup and then read requests, calling srv.Handler to reply to them.
3080 // Files containing a certificate and matching private key for the
3081 // server must be provided if neither the Server's
3082 // TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
3083 // If the certificate is signed by a certificate authority, the
3084 // certFile should be the concatenation of the server's certificate,
3085 // any intermediates, and the CA's certificate.
3087 // ServeTLS always returns a non-nil error. After Shutdown or Close, the
3088 // returned error is ErrServerClosed.
3089 func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
3090 // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
3091 // before we clone it and create the TLS Listener.
3092 if err := srv.setupHTTP2_ServeTLS(); err != nil {
3096 config := cloneTLSConfig(srv.TLSConfig)
3097 if !strSliceContains(config.NextProtos, "http/1.1") {
3098 config.NextProtos = append(config.NextProtos, "http/1.1")
3101 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
3102 if !configHasCert || certFile != "" || keyFile != "" {
3104 config.Certificates = make([]tls.Certificate, 1)
3105 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
3111 tlsListener := tls.NewListener(l, config)
3112 return srv.Serve(tlsListener)
3115 // trackListener adds or removes a net.Listener to the set of tracked
3118 // We store a pointer to interface in the map set, in case the
3119 // net.Listener is not comparable. This is safe because we only call
3120 // trackListener via Serve and can track+defer untrack the same
3121 // pointer to local variable there. We never need to compare a
3122 // Listener from another caller.
3124 // It reports whether the server is still up (not Shutdown or Closed).
3125 func (s *Server) trackListener(ln *net.Listener, add bool) bool {
3128 if s.listeners == nil {
3129 s.listeners = make(map[*net.Listener]struct{})
3132 if s.shuttingDown() {
3135 s.listeners[ln] = struct{}{}
3136 s.listenerGroup.Add(1)
3138 delete(s.listeners, ln)
3139 s.listenerGroup.Done()
3144 func (s *Server) trackConn(c *conn, add bool) {
3147 if s.activeConn == nil {
3148 s.activeConn = make(map[*conn]struct{})
3151 s.activeConn[c] = struct{}{}
3153 delete(s.activeConn, c)
3157 func (s *Server) idleTimeout() time.Duration {
3158 if s.IdleTimeout != 0 {
3159 return s.IdleTimeout
3161 return s.ReadTimeout
3164 func (s *Server) readHeaderTimeout() time.Duration {
3165 if s.ReadHeaderTimeout != 0 {
3166 return s.ReadHeaderTimeout
3168 return s.ReadTimeout
3171 func (s *Server) doKeepAlives() bool {
3172 return !s.disableKeepAlives.Load() && !s.shuttingDown()
3175 func (s *Server) shuttingDown() bool {
3176 return s.inShutdown.Load()
3179 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
3180 // By default, keep-alives are always enabled. Only very
3181 // resource-constrained environments or servers in the process of
3182 // shutting down should disable them.
3183 func (srv *Server) SetKeepAlivesEnabled(v bool) {
3185 srv.disableKeepAlives.Store(false)
3188 srv.disableKeepAlives.Store(true)
3190 // Close idle HTTP/1 conns:
3191 srv.closeIdleConns()
3193 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
3196 func (s *Server) logf(format string, args ...any) {
3197 if s.ErrorLog != nil {
3198 s.ErrorLog.Printf(format, args...)
3200 log.Printf(format, args...)
3204 // logf prints to the ErrorLog of the *Server associated with request r
3205 // via ServerContextKey. If there's no associated server, or if ErrorLog
3206 // is nil, logging is done via the log package's standard logger.
3207 func logf(r *Request, format string, args ...any) {
3208 s, _ := r.Context().Value(ServerContextKey).(*Server)
3209 if s != nil && s.ErrorLog != nil {
3210 s.ErrorLog.Printf(format, args...)
3212 log.Printf(format, args...)
3216 // ListenAndServe listens on the TCP network address addr and then calls
3217 // Serve with handler to handle requests on incoming connections.
3218 // Accepted connections are configured to enable TCP keep-alives.
3220 // The handler is typically nil, in which case the DefaultServeMux is used.
3222 // ListenAndServe always returns a non-nil error.
3223 func ListenAndServe(addr string, handler Handler) error {
3224 server := &Server{Addr: addr, Handler: handler}
3225 return server.ListenAndServe()
3228 // ListenAndServeTLS acts identically to ListenAndServe, except that it
3229 // expects HTTPS connections. Additionally, files containing a certificate and
3230 // matching private key for the server must be provided. If the certificate
3231 // is signed by a certificate authority, the certFile should be the concatenation
3232 // of the server's certificate, any intermediates, and the CA's certificate.
3233 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
3234 server := &Server{Addr: addr, Handler: handler}
3235 return server.ListenAndServeTLS(certFile, keyFile)
3238 // ListenAndServeTLS listens on the TCP network address srv.Addr and
3239 // then calls ServeTLS to handle requests on incoming TLS connections.
3240 // Accepted connections are configured to enable TCP keep-alives.
3242 // Filenames containing a certificate and matching private key for the
3243 // server must be provided if neither the Server's TLSConfig.Certificates
3244 // nor TLSConfig.GetCertificate are populated. If the certificate is
3245 // signed by a certificate authority, the certFile should be the
3246 // concatenation of the server's certificate, any intermediates, and
3247 // the CA's certificate.
3249 // If srv.Addr is blank, ":https" is used.
3251 // ListenAndServeTLS always returns a non-nil error. After Shutdown or
3252 // Close, the returned error is ErrServerClosed.
3253 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
3254 if srv.shuttingDown() {
3255 return ErrServerClosed
3262 ln, err := net.Listen("tcp", addr)
3269 return srv.ServeTLS(ln, certFile, keyFile)
3272 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
3273 // srv and reports whether there was an error setting it up. If it is
3274 // not configured for policy reasons, nil is returned.
3275 func (srv *Server) setupHTTP2_ServeTLS() error {
3276 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
3277 return srv.nextProtoErr
3280 // setupHTTP2_Serve is called from (*Server).Serve and conditionally
3281 // configures HTTP/2 on srv using a more conservative policy than
3282 // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
3283 // and may be called concurrently. See shouldConfigureHTTP2ForServe.
3285 // The tests named TestTransportAutomaticHTTP2* and
3286 // TestConcurrentServerServe in server_test.go demonstrate some
3287 // of the supported use cases and motivations.
3288 func (srv *Server) setupHTTP2_Serve() error {
3289 srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
3290 return srv.nextProtoErr
3293 func (srv *Server) onceSetNextProtoDefaults_Serve() {
3294 if srv.shouldConfigureHTTP2ForServe() {
3295 srv.onceSetNextProtoDefaults()
3299 var http2server = godebug.New("http2server")
3301 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
3302 // configured otherwise. (by setting srv.TLSNextProto non-nil)
3303 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
3304 func (srv *Server) onceSetNextProtoDefaults() {
3305 if omitBundledHTTP2 {
3308 if http2server.Value() == "0" {
3309 http2server.IncNonDefault()
3312 // Enable HTTP/2 by default if the user hasn't otherwise
3313 // configured their TLSNextProto map.
3314 if srv.TLSNextProto == nil {
3315 conf := &http2Server{
3316 NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
3318 srv.nextProtoErr = http2ConfigureServer(srv, conf)
3322 // TimeoutHandler returns a Handler that runs h with the given time limit.
3324 // The new Handler calls h.ServeHTTP to handle each request, but if a
3325 // call runs for longer than its time limit, the handler responds with
3326 // a 503 Service Unavailable error and the given message in its body.
3327 // (If msg is empty, a suitable default message will be sent.)
3328 // After such a timeout, writes by h to its ResponseWriter will return
3329 // ErrHandlerTimeout.
3331 // TimeoutHandler supports the Pusher interface but does not support
3332 // the Hijacker or Flusher interfaces.
3333 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
3334 return &timeoutHandler{
3341 // ErrHandlerTimeout is returned on ResponseWriter Write calls
3342 // in handlers which have timed out.
3343 var ErrHandlerTimeout = errors.New("http: Handler timeout")
3345 type timeoutHandler struct {
3350 // When set, no context will be created and this context will
3352 testContext context.Context
3355 func (h *timeoutHandler) errorBody() string {
3359 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3362 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
3363 ctx := h.testContext
3365 var cancelCtx context.CancelFunc
3366 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
3369 r = r.WithContext(ctx)
3370 done := make(chan struct{})
3371 tw := &timeoutWriter{
3376 panicChan := make(chan any, 1)
3379 if p := recover(); p != nil {
3383 h.handler.ServeHTTP(tw, r)
3387 case p := <-panicChan:
3391 defer tw.mu.Unlock()
3393 for k, vv := range tw.h {
3396 if !tw.wroteHeader {
3399 w.WriteHeader(tw.code)
3400 w.Write(tw.wbuf.Bytes())
3403 defer tw.mu.Unlock()
3404 switch err := ctx.Err(); err {
3405 case context.DeadlineExceeded:
3406 w.WriteHeader(StatusServiceUnavailable)
3407 io.WriteString(w, h.errorBody())
3408 tw.err = ErrHandlerTimeout
3410 w.WriteHeader(StatusServiceUnavailable)
3416 type timeoutWriter struct {
3428 var _ Pusher = (*timeoutWriter)(nil)
3430 // Push implements the Pusher interface.
3431 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
3432 if pusher, ok := tw.w.(Pusher); ok {
3433 return pusher.Push(target, opts)
3435 return ErrNotSupported
3438 func (tw *timeoutWriter) Header() Header { return tw.h }
3440 func (tw *timeoutWriter) Write(p []byte) (int, error) {
3442 defer tw.mu.Unlock()
3446 if !tw.wroteHeader {
3447 tw.writeHeaderLocked(StatusOK)
3449 return tw.wbuf.Write(p)
3452 func (tw *timeoutWriter) writeHeaderLocked(code int) {
3453 checkWriteHeaderCode(code)
3458 case tw.wroteHeader:
3460 caller := relevantCaller()
3461 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
3464 tw.wroteHeader = true
3469 func (tw *timeoutWriter) WriteHeader(code int) {
3471 defer tw.mu.Unlock()
3472 tw.writeHeaderLocked(code)
3475 // onceCloseListener wraps a net.Listener, protecting it from
3476 // multiple Close calls.
3477 type onceCloseListener struct {
3483 func (oc *onceCloseListener) Close() error {
3484 oc.once.Do(oc.close)
3488 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
3490 // globalOptionsHandler responds to "OPTIONS *" requests.
3491 type globalOptionsHandler struct{}
3493 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
3494 w.Header().Set("Content-Length", "0")
3495 if r.ContentLength != 0 {
3496 // Read up to 4KB of OPTIONS body (as mentioned in the
3497 // spec as being reserved for future use), but anything
3498 // over that is considered a waste of server resources
3499 // (or an attack) and we abort and close the connection,
3500 // courtesy of MaxBytesReader's EOF behavior.
3501 mb := MaxBytesReader(w, r.Body, 4<<10)
3502 io.Copy(io.Discard, mb)
3506 // initALPNRequest is an HTTP handler that initializes certain
3507 // uninitialized fields in its *Request. Such partially-initialized
3508 // Requests come from ALPN protocol handlers.
3509 type initALPNRequest struct {
3515 // BaseContext is an exported but unadvertised http.Handler method
3516 // recognized by x/net/http2 to pass down a context; the TLSNextProto
3517 // API predates context support so we shoehorn through the only
3518 // interface we have available.
3519 func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
3521 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
3523 req.TLS = &tls.ConnectionState{}
3524 *req.TLS = h.c.ConnectionState()
3526 if req.Body == nil {
3529 if req.RemoteAddr == "" {
3530 req.RemoteAddr = h.c.RemoteAddr().String()
3532 h.h.ServeHTTP(rw, req)
3535 // loggingConn is used for debugging.
3536 type loggingConn struct {
3542 uniqNameMu sync.Mutex
3543 uniqNameNext = make(map[string]int)
3546 func newLoggingConn(baseName string, c net.Conn) net.Conn {
3548 defer uniqNameMu.Unlock()
3549 uniqNameNext[baseName]++
3550 return &loggingConn{
3551 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
3556 func (c *loggingConn) Write(p []byte) (n int, err error) {
3557 log.Printf("%s.Write(%d) = ....", c.name, len(p))
3558 n, err = c.Conn.Write(p)
3559 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
3563 func (c *loggingConn) Read(p []byte) (n int, err error) {
3564 log.Printf("%s.Read(%d) = ....", c.name, len(p))
3565 n, err = c.Conn.Read(p)
3566 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
3570 func (c *loggingConn) Close() (err error) {
3571 log.Printf("%s.Close() = ...", c.name)
3572 err = c.Conn.Close()
3573 log.Printf("%s.Close() = %v", c.name, err)
3577 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
3578 // It only contains one field (and a pointer field at that), so it
3579 // fits in an interface value without an extra allocation.
3580 type checkConnErrorWriter struct {
3584 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
3585 n, err = w.c.rwc.Write(p)
3586 if err != nil && w.c.werr == nil {
3593 func numLeadingCRorLF(v []byte) (n int) {
3594 for _, b := range v {
3595 if b == '\r' || b == '\n' {
3605 func strSliceContains(ss []string, s string) bool {
3606 for _, v := range ss {
3614 // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
3615 // looks like it might've been a misdirected plaintext HTTP request.
3616 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
3617 switch string(hdr[:]) {
3618 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
3624 // MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.
3625 func MaxBytesHandler(h Handler, n int64) Handler {
3626 return HandlerFunc(func(w ResponseWriter, r *Request) {
3628 r2.Body = MaxBytesReader(w, r.Body, n)