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.
31 "golang_org/x/net/http/httpguts"
34 // Errors used by the HTTP server.
36 // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
37 // when the HTTP method or response code does not permit a
39 ErrBodyNotAllowed
= errors
.New("http: request method or response status code does not allow body")
41 // ErrHijacked is returned by ResponseWriter.Write calls when
42 // the underlying connection has been hijacked using the
43 // Hijacker interface. A zero-byte write on a hijacked
44 // connection will return ErrHijacked without any other side
46 ErrHijacked
= errors
.New("http: connection has been hijacked")
48 // ErrContentLength is returned by ResponseWriter.Write calls
49 // when a Handler set a Content-Length response header with a
50 // declared size and then attempted to write more bytes than
52 ErrContentLength
= errors
.New("http: wrote more than the declared Content-Length")
54 // Deprecated: ErrWriteAfterFlush is no longer returned by
55 // anything in the net/http package. Callers should not
56 // compare errors against this variable.
57 ErrWriteAfterFlush
= errors
.New("unused")
60 // A Handler responds to an HTTP request.
62 // ServeHTTP should write reply headers and data to the ResponseWriter
63 // and then return. Returning signals that the request is finished; it
64 // is not valid to use the ResponseWriter or read from the
65 // Request.Body after or concurrently with the completion of the
68 // Depending on the HTTP client software, HTTP protocol version, and
69 // any intermediaries between the client and the Go server, it may not
70 // be possible to read from the Request.Body after writing to the
71 // ResponseWriter. Cautious handlers should read the Request.Body
72 // first, and then reply.
74 // Except for reading the body, handlers should not modify the
77 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
78 // that the effect of the panic was isolated to the active request.
79 // It recovers the panic, logs a stack trace to the server error log,
80 // and either closes the network connection or sends an HTTP/2
81 // RST_STREAM, depending on the HTTP protocol. To abort a handler so
82 // the client sees an interrupted response but the server doesn't log
83 // an error, panic with the value ErrAbortHandler.
84 type Handler
interface {
85 ServeHTTP(ResponseWriter
, *Request
)
88 // A ResponseWriter interface is used by an HTTP handler to
89 // construct an HTTP response.
91 // A ResponseWriter may not be used after the Handler.ServeHTTP method
93 type ResponseWriter
interface {
94 // Header returns the header map that will be sent by
95 // WriteHeader. The Header map also is the mechanism with which
96 // Handlers can set HTTP trailers.
98 // Changing the header map after a call to WriteHeader (or
99 // Write) has no effect unless the modified headers are
102 // There are two ways to set Trailers. The preferred way is to
103 // predeclare in the headers which trailers you will later
104 // send by setting the "Trailer" header to the names of the
105 // trailer keys which will come later. In this case, those
106 // keys of the Header map are treated as if they were
107 // trailers. See the example. The second way, for trailer
108 // keys not known to the Handler until after the first Write,
109 // is to prefix the Header map keys with the TrailerPrefix
110 // constant value. See TrailerPrefix.
112 // To suppress automatic response headers (such as "Date"), set
113 // their value to nil.
116 // Write writes the data to the connection as part of an HTTP reply.
118 // If WriteHeader has not yet been called, Write calls
119 // WriteHeader(http.StatusOK) before writing the data. If the Header
120 // does not contain a Content-Type line, Write adds a Content-Type set
121 // to the result of passing the initial 512 bytes of written data to
122 // DetectContentType. Additionally, if the total size of all written
123 // data is under a few KB and there are no Flush calls, the
124 // Content-Length header is added automatically.
126 // Depending on the HTTP protocol version and the client, calling
127 // Write or WriteHeader may prevent future reads on the
128 // Request.Body. For HTTP/1.x requests, handlers should read any
129 // needed request body data before writing the response. Once the
130 // headers have been flushed (due to either an explicit Flusher.Flush
131 // call or writing enough data to trigger a flush), the request body
132 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
133 // handlers to continue to read the request body while concurrently
134 // writing the response. However, such behavior may not be supported
135 // by all HTTP/2 clients. Handlers should read before writing if
136 // possible to maximize compatibility.
137 Write([]byte) (int, error
)
139 // WriteHeader sends an HTTP response header with the provided
142 // If WriteHeader is not called explicitly, the first call to Write
143 // will trigger an implicit WriteHeader(http.StatusOK).
144 // Thus explicit calls to WriteHeader are mainly used to
147 // The provided code must be a valid HTTP 1xx-5xx status code.
148 // Only one header may be written. Go does not currently
149 // support sending user-defined 1xx informational headers,
150 // with the exception of 100-continue response header that the
151 // Server sends automatically when the Request.Body is read.
152 WriteHeader(statusCode
int)
155 // The Flusher interface is implemented by ResponseWriters that allow
156 // an HTTP handler to flush buffered data to the client.
158 // The default HTTP/1.x and HTTP/2 ResponseWriter implementations
159 // support Flusher, but ResponseWriter wrappers may not. Handlers
160 // should always test for this ability at runtime.
162 // Note that even for ResponseWriters that support Flush,
163 // if the client is connected through an HTTP proxy,
164 // the buffered data may not reach the client until the response
166 type Flusher
interface {
167 // Flush sends any buffered data to the client.
171 // The Hijacker interface is implemented by ResponseWriters that allow
172 // an HTTP handler to take over the connection.
174 // The default ResponseWriter for HTTP/1.x connections supports
175 // Hijacker, but HTTP/2 connections intentionally do not.
176 // ResponseWriter wrappers may also not support Hijacker. Handlers
177 // should always test for this ability at runtime.
178 type Hijacker
interface {
179 // Hijack lets the caller take over the connection.
180 // After a call to Hijack the HTTP server library
181 // will not do anything else with the connection.
183 // It becomes the caller's responsibility to manage
184 // and close the connection.
186 // The returned net.Conn may have read or write deadlines
187 // already set, depending on the configuration of the
188 // Server. It is the caller's responsibility to set
189 // or clear those deadlines as needed.
191 // The returned bufio.Reader may contain unprocessed buffered
192 // data from the client.
194 // After a call to Hijack, the original Request.Body must not
195 // be used. The original Request's Context remains valid and
196 // is not canceled until the Request's ServeHTTP method
198 Hijack() (net
.Conn
, *bufio
.ReadWriter
, error
)
201 // The CloseNotifier interface is implemented by ResponseWriters which
202 // allow detecting when the underlying connection has gone away.
204 // This mechanism can be used to cancel long operations on the server
205 // if the client has disconnected before the response is ready.
207 // Deprecated: the CloseNotifier interface predates Go's context package.
208 // New code should use Request.Context instead.
209 type CloseNotifier
interface {
210 // CloseNotify returns a channel that receives at most a
211 // single value (true) when the client connection has gone
214 // CloseNotify may wait to notify until Request.Body has been
217 // After the Handler has returned, there is no guarantee
218 // that the channel receives a value.
220 // If the protocol is HTTP/1.1 and CloseNotify is called while
221 // processing an idempotent request (such a GET) while
222 // HTTP/1.1 pipelining is in use, the arrival of a subsequent
223 // pipelined request may cause a value to be sent on the
224 // returned channel. In practice HTTP/1.1 pipelining is not
225 // enabled in browsers and not seen often in the wild. If this
226 // is a problem, use HTTP/2 or only use CloseNotify on methods
228 CloseNotify() <-chan bool
232 // ServerContextKey is a context key. It can be used in HTTP
233 // handlers with context.WithValue to access the server that
234 // started the handler. The associated value will be of
236 ServerContextKey
= &contextKey
{"http-server"}
238 // LocalAddrContextKey is a context key. It can be used in
239 // HTTP handlers with context.WithValue to access the local
240 // address the connection arrived on.
241 // The associated value will be of type net.Addr.
242 LocalAddrContextKey
= &contextKey
{"local-addr"}
245 // A conn represents the server side of an HTTP connection.
247 // server is the server on which the connection arrived.
248 // Immutable; never nil.
251 // cancelCtx cancels the connection-level context.
252 cancelCtx context
.CancelFunc
254 // rwc is the underlying network connection.
255 // This is never wrapped by other types and is the value given out
256 // to CloseNotifier callers. It is usually of type *net.TCPConn or
260 // remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
261 // inside the Listener's Accept goroutine, as some implementations block.
262 // It is populated immediately inside the (*conn).serve goroutine.
263 // This is the value of a Handler's (*Request).RemoteAddr.
266 // tlsState is the TLS connection state when using TLS.
267 // nil means not TLS.
268 tlsState
*tls
.ConnectionState
270 // werr is set to the first write error to rwc.
271 // It is set via checkConnErrorWriter{w}, where bufw writes.
274 // r is bufr's read source. It's a wrapper around rwc that provides
275 // io.LimitedReader-style limiting (while reading request headers)
276 // and functionality to support CloseNotifier. See *connReader docs.
279 // bufr reads from r.
282 // bufw writes to checkConnErrorWriter{c}, which populates werr on error.
285 // lastMethod is the method of the most recent request
286 // on this connection, if any.
289 curReq atomic
.Value
// of *response (which has a Request in it)
291 curState
struct{ atomic
uint64 } // packed (unixtime<<8|uint8(ConnState))
293 // mu guards hijackedv
296 // hijackedv is whether this connection has been hijacked
297 // by a Handler with the Hijacker interface.
298 // It is guarded by mu.
302 func (c
*conn
) hijacked() bool {
308 // c.mu must be held.
309 func (c
*conn
) hijackLocked() (rwc net
.Conn
, buf
*bufio
.ReadWriter
, err error
) {
311 return nil, nil, ErrHijacked
313 c
.r
.abortPendingRead()
317 rwc
.SetDeadline(time
.Time
{})
319 buf
= bufio
.NewReadWriter(c
.bufr
, bufio
.NewWriter(rwc
))
321 if _
, err
:= c
.bufr
.Peek(c
.bufr
.Buffered() + 1); err
!= nil {
322 return nil, nil, fmt
.Errorf("unexpected Peek failure reading buffered byte: %v", err
)
325 c
.setState(rwc
, StateHijacked
)
329 // This should be >= 512 bytes for DetectContentType,
330 // but otherwise it's somewhat arbitrary.
331 const bufferBeforeChunkingSize
= 2048
333 // chunkWriter writes to a response's conn buffer, and is the writer
334 // wrapped by the response.bufw buffered writer.
336 // chunkWriter also is responsible for finalizing the Header, including
337 // conditionally setting the Content-Type and setting a Content-Length
338 // in cases where the handler's final output is smaller than the buffer
339 // size. It also conditionally adds chunk headers, when in chunking mode.
341 // See the comment above (*response).Write for the entire write flow.
342 type chunkWriter
struct {
345 // header is either nil or a deep clone of res.handlerHeader
346 // at the time of res.writeHeader, if res.writeHeader is
347 // called and extra buffering is being done to calculate
348 // Content-Type and/or Content-Length.
351 // wroteHeader tells whether the header's been written to "the
352 // wire" (or rather: w.conn.buf). this is unlike
353 // (*response).wroteHeader, which tells only whether it was
354 // logically written.
357 // set by the writeHeader method:
358 chunking
bool // using chunked transfer encoding for reply body
362 crlf
= []byte("\r\n")
363 colonSpace
= []byte(": ")
366 func (cw
*chunkWriter
) Write(p
[]byte) (n
int, err error
) {
370 if cw
.res
.req
.Method
== "HEAD" {
375 _
, err
= fmt
.Fprintf(cw
.res
.conn
.bufw
, "%x\r\n", len(p
))
377 cw
.res
.conn
.rwc
.Close()
381 n
, err
= cw
.res
.conn
.bufw
.Write(p
)
382 if cw
.chunking
&& err
== nil {
383 _
, err
= cw
.res
.conn
.bufw
.Write(crlf
)
386 cw
.res
.conn
.rwc
.Close()
391 func (cw
*chunkWriter
) flush() {
395 cw
.res
.conn
.bufw
.Flush()
398 func (cw
*chunkWriter
) close() {
403 bw
:= cw
.res
.conn
.bufw
// conn's bufio writer
404 // zero chunk to mark EOF
405 bw
.WriteString("0\r\n")
406 if trailers
:= cw
.res
.finalTrailers(); trailers
!= nil {
407 trailers
.Write(bw
) // the writer handles noting errors
409 // final blank line after the trailers (whether
411 bw
.WriteString("\r\n")
415 // A response represents the server side of an HTTP response.
416 type response
struct {
418 req
*Request
// request for this response
419 reqBody io
.ReadCloser
420 cancelCtx context
.CancelFunc
// when ServeHTTP exits
421 wroteHeader
bool // reply header has been (logically) written
422 wroteContinue
bool // 100 Continue response was written
423 wants10KeepAlive
bool // HTTP/1.0 w/ Connection "keep-alive"
424 wantsClose
bool // HTTP request has Connection "close"
426 w
*bufio
.Writer
// buffers output in chunks to chunkWriter
429 // handlerHeader is the Header that Handlers get access to,
430 // which may be retained and mutated even after WriteHeader.
431 // handlerHeader is copied into cw.header at WriteHeader
432 // time, and privately mutated thereafter.
434 calledHeader
bool // handler accessed handlerHeader via Header
436 written
int64 // number of bytes written in body
437 contentLength
int64 // explicitly-declared Content-Length; or -1
438 status
int // status code passed to WriteHeader
440 // close connection after this reply. set on request and
441 // updated after response from handler if there's a
442 // "Connection: keep-alive" response header and a
446 // requestBodyLimitHit is set by requestTooLarge when
447 // maxBytesReader hits its max size. It is checked in
448 // WriteHeader, to make sure we don't consume the
449 // remaining request body to try to advance to the next HTTP
450 // request. Instead, when this is set, we stop reading
451 // subsequent requests on this connection and stop reading
453 requestBodyLimitHit
bool
455 // trailers are the headers to be sent after the handler
456 // finishes writing the body. This field is initialized from
457 // the Trailer response header when the response header is
461 handlerDone atomicBool
// set true when the handler exits
463 // Buffers for Date, Content-Length, and status code
464 dateBuf
[len(TimeFormat
)]byte
468 // closeNotifyCh is the channel returned by CloseNotify.
469 // TODO(bradfitz): this is currently (for Go 1.8) always
470 // non-nil. Make this lazily-created again as it used to be?
471 closeNotifyCh
chan bool
472 didCloseNotify
int32 // atomic (only 0->1 winner should send)
475 // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
476 // that, if present, signals that the map entry is actually for
477 // the response trailers, and not the response headers. The prefix
478 // is stripped after the ServeHTTP call finishes and the values are
479 // sent in the trailers.
481 // This mechanism is intended only for trailers that are not known
482 // prior to the headers being written. If the set of trailers is fixed
483 // or known before the header is written, the normal Go trailers mechanism
485 // https://golang.org/pkg/net/http/#ResponseWriter
486 // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
487 const TrailerPrefix
= "Trailer:"
489 // finalTrailers is called after the Handler exits and returns a non-nil
490 // value if the Handler set any trailers.
491 func (w
*response
) finalTrailers() Header
{
493 for k
, vv
:= range w
.handlerHeader
{
494 if strings
.HasPrefix(k
, TrailerPrefix
) {
498 t
[strings
.TrimPrefix(k
, TrailerPrefix
)] = vv
501 for _
, k
:= range w
.trailers
{
505 for _
, v
:= range w
.handlerHeader
[k
] {
512 type atomicBool
int32
514 func (b
*atomicBool
) isSet() bool { return atomic
.LoadInt32((*int32)(b
)) != 0 }
515 func (b
*atomicBool
) setTrue() { atomic
.StoreInt32((*int32)(b
), 1) }
517 // declareTrailer is called for each Trailer header when the
518 // response header is written. It notes that a header will need to be
519 // written in the trailers at the end of the response.
520 func (w
*response
) declareTrailer(k
string) {
521 k
= CanonicalHeaderKey(k
)
522 if !httpguts
.ValidTrailerHeader(k
) {
523 // Forbidden by RFC 7230, section 4.1.2
526 w
.trailers
= append(w
.trailers
, k
)
529 // requestTooLarge is called by maxBytesReader when too much input has
530 // been read from the client.
531 func (w
*response
) requestTooLarge() {
532 w
.closeAfterReply
= true
533 w
.requestBodyLimitHit
= true
535 w
.Header().Set("Connection", "close")
539 // needsSniff reports whether a Content-Type still needs to be sniffed.
540 func (w
*response
) needsSniff() bool {
541 _
, haveType
:= w
.handlerHeader
["Content-Type"]
542 return !w
.cw
.wroteHeader
&& !haveType
&& w
.written
< sniffLen
545 // writerOnly hides an io.Writer value's optional ReadFrom method
547 type writerOnly
struct {
551 func srcIsRegularFile(src io
.Reader
) (isRegular
bool, err error
) {
552 switch v
:= src
.(type) {
558 return fi
.Mode().IsRegular(), nil
559 case *io
.LimitedReader
:
560 return srcIsRegularFile(v
.R
)
566 // ReadFrom is here to optimize copying from an *os.File regular file
567 // to a *net.TCPConn with sendfile.
568 func (w
*response
) ReadFrom(src io
.Reader
) (n
int64, err error
) {
569 // Our underlying w.conn.rwc is usually a *TCPConn (with its
570 // own ReadFrom method). If not, or if our src isn't a regular
571 // file, just fall back to the normal copy method.
572 rf
, ok
:= w
.conn
.rwc
.(io
.ReaderFrom
)
573 regFile
, err
:= srcIsRegularFile(src
)
578 bufp
:= copyBufPool
.Get().(*[]byte)
579 defer copyBufPool
.Put(bufp
)
580 return io
.CopyBuffer(writerOnly
{w
}, src
, *bufp
)
586 w
.WriteHeader(StatusOK
)
590 n0
, err
:= io
.Copy(writerOnly
{w
}, io
.LimitReader(src
, sniffLen
))
597 w
.w
.Flush() // get rid of any previous writes
598 w
.cw
.flush() // make sure Header is written; flush data to rwc
600 // Now that cw has been flushed, its chunking field is guaranteed initialized.
601 if !w
.cw
.chunking
&& w
.bodyAllowed() {
602 n0
, err
:= rf
.ReadFrom(src
)
608 n0
, err
:= io
.Copy(writerOnly
{w
}, src
)
613 // debugServerConnections controls whether all server connections are wrapped
614 // with a verbose logging wrapper.
615 const debugServerConnections
= false
617 // Create new connection from rwc.
618 func (srv
*Server
) newConn(rwc net
.Conn
) *conn
{
623 if debugServerConnections
{
624 c
.rwc
= newLoggingConn("server", c
.rwc
)
629 type readResult
struct {
632 b
byte // byte read, if n == 1
635 // connReader is the io.Reader wrapper used by *conn. It combines a
636 // selectively-activated io.LimitedReader (to bound request header
637 // read sizes) with support for selectively keeping an io.Reader.Read
638 // call blocked in a background goroutine to wait for activity and
639 // trigger a CloseNotifier channel.
640 type connReader
struct {
643 mu sync
.Mutex
// guards following
648 aborted
bool // set true before conn.rwc deadline is set to past
649 remain
int64 // bytes remaining
652 func (cr
*connReader
) lock() {
655 cr
.cond
= sync
.NewCond(&cr
.mu
)
659 func (cr
*connReader
) unlock() { cr
.mu
.Unlock() }
661 func (cr
*connReader
) startBackgroundRead() {
665 panic("invalid concurrent Body.Read call")
671 cr
.conn
.rwc
.SetReadDeadline(time
.Time
{})
672 go cr
.backgroundRead()
675 func (cr
*connReader
) backgroundRead() {
676 n
, err
:= cr
.conn
.rwc
.Read(cr
.byteBuf
[:])
680 // We were past the end of the previous request's body already
681 // (since we wouldn't be in a background read otherwise), so
682 // this is a pipelined HTTP request. Prior to Go 1.11 we used to
683 // send on the CloseNotify channel and cancel the context here,
684 // but the behavior was documented as only "may", and we only
685 // did that because that's how CloseNotify accidentally behaved
686 // in very early Go releases prior to context support. Once we
687 // added context support, people used a Handler's
688 // Request.Context() and passed it along. Having that context
689 // cancel on pipelined HTTP requests caused problems.
690 // Fortunately, almost nothing uses HTTP/1.x pipelining.
691 // Unfortunately, apt-get does, or sometimes does.
692 // New Go 1.11 behavior: don't fire CloseNotify or cancel
693 // contexts on pipelined requests. Shouldn't affect people, but
694 // fixes cases like Issue 23921. This does mean that a client
695 // closing their TCP connection after sending a pipelined
696 // request won't cancel the context, but we'll catch that on any
697 // write failure (in checkConnErrorWriter.Write).
698 // If the server never writes, yes, there are still contrived
699 // server & client behaviors where this fails to ever cancel the
700 // context, but that's kinda why HTTP/1.x pipelining died
703 if ne
, ok
:= err
.(net
.Error
); ok
&& cr
.aborted
&& ne
.Timeout() {
704 // Ignore this error. It's the expected error from
705 // another goroutine calling abortPendingRead.
706 } else if err
!= nil {
707 cr
.handleReadError(err
)
715 func (cr
*connReader
) abortPendingRead() {
722 cr
.conn
.rwc
.SetReadDeadline(aLongTimeAgo
)
726 cr
.conn
.rwc
.SetReadDeadline(time
.Time
{})
729 func (cr
*connReader
) setReadLimit(remain
int64) { cr
.remain
= remain
}
730 func (cr
*connReader
) setInfiniteReadLimit() { cr
.remain
= maxInt64
}
731 func (cr
*connReader
) hitReadLimit() bool { return cr
.remain
<= 0 }
733 // handleReadError is called whenever a Read from the client returns a
736 // The provided non-nil err is almost always io.EOF or a "use of
737 // closed network connection". In any case, the error is not
738 // particularly interesting, except perhaps for debugging during
739 // development. Any error means the connection is dead and we should
742 // It may be called from multiple goroutines.
743 func (cr
*connReader
) handleReadError(_ error
) {
748 // may be called from multiple goroutines.
749 func (cr
*connReader
) closeNotify() {
750 res
, _
:= cr
.conn
.curReq
.Load().(*response
)
752 if atomic
.CompareAndSwapInt32(&res
.didCloseNotify
, 0, 1) {
753 res
.closeNotifyCh
<- true
758 func (cr
*connReader
) Read(p
[]byte) (n
int, err error
) {
762 if cr
.conn
.hijacked() {
763 panic("invalid Body.Read call. After hijacked, the original Request must not be used")
765 panic("invalid concurrent Body.Read call")
767 if cr
.hitReadLimit() {
775 if int64(len(p
)) > cr
.remain
{
786 n
, err
= cr
.conn
.rwc
.Read(p
)
791 cr
.handleReadError(err
)
793 cr
.remain
-= int64(n
)
801 bufioReaderPool sync
.Pool
802 bufioWriter2kPool sync
.Pool
803 bufioWriter4kPool sync
.Pool
806 var copyBufPool
= sync
.Pool
{
807 New
: func() interface{} {
808 b
:= make([]byte, 32*1024)
813 func bufioWriterPool(size
int) *sync
.Pool
{
816 return &bufioWriter2kPool
818 return &bufioWriter4kPool
823 func newBufioReader(r io
.Reader
) *bufio
.Reader
{
824 if v
:= bufioReaderPool
.Get(); v
!= nil {
825 br
:= v
.(*bufio
.Reader
)
829 // Note: if this reader size is ever changed, update
830 // TestHandlerBodyClose's assumptions.
831 return bufio
.NewReader(r
)
834 func putBufioReader(br
*bufio
.Reader
) {
836 bufioReaderPool
.Put(br
)
839 func newBufioWriterSize(w io
.Writer
, size
int) *bufio
.Writer
{
840 pool
:= bufioWriterPool(size
)
842 if v
:= pool
.Get(); v
!= nil {
843 bw
:= v
.(*bufio
.Writer
)
848 return bufio
.NewWriterSize(w
, size
)
851 func putBufioWriter(bw
*bufio
.Writer
) {
853 if pool
:= bufioWriterPool(bw
.Available()); pool
!= nil {
858 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
859 // in an HTTP request.
860 // This can be overridden by setting Server.MaxHeaderBytes.
861 const DefaultMaxHeaderBytes
= 1 << 20 // 1 MB
863 func (srv
*Server
) maxHeaderBytes() int {
864 if srv
.MaxHeaderBytes
> 0 {
865 return srv
.MaxHeaderBytes
867 return DefaultMaxHeaderBytes
870 func (srv
*Server
) initialReadLimitSize() int64 {
871 return int64(srv
.maxHeaderBytes()) + 4096 // bufio slop
874 // wrapper around io.ReadCloser which on first read, sends an
875 // HTTP/1.1 100 Continue header
876 type expectContinueReader
struct {
878 readCloser io
.ReadCloser
883 func (ecr
*expectContinueReader
) Read(p
[]byte) (n
int, err error
) {
885 return 0, ErrBodyReadAfterClose
887 if !ecr
.resp
.wroteContinue
&& !ecr
.resp
.conn
.hijacked() {
888 ecr
.resp
.wroteContinue
= true
889 ecr
.resp
.conn
.bufw
.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
890 ecr
.resp
.conn
.bufw
.Flush()
892 n
, err
= ecr
.readCloser
.Read(p
)
899 func (ecr
*expectContinueReader
) Close() error
{
901 return ecr
.readCloser
.Close()
904 // TimeFormat is the time format to use when generating times in HTTP
905 // headers. It is like time.RFC1123 but hard-codes GMT as the time
906 // zone. The time being formatted must be in UTC for Format to
907 // generate the correct format.
909 // For parsing this time format, see ParseTime.
910 const TimeFormat
= "Mon, 02 Jan 2006 15:04:05 GMT"
912 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
913 func appendTime(b
[]byte, t time
.Time
) []byte {
914 const days
= "SunMonTueWedThuFriSat"
915 const months
= "JanFebMarAprMayJunJulAugSepOctNovDec"
918 yy
, mm
, dd
:= t
.Date()
919 hh
, mn
, ss
:= t
.Clock()
920 day
:= days
[3*t
.Weekday():]
921 mon
:= months
[3*(mm
-1):]
924 day
[0], day
[1], day
[2], ',', ' ',
925 byte('0'+dd
/10), byte('0'+dd%10
), ' ',
926 mon
[0], mon
[1], mon
[2], ' ',
927 byte('0'+yy
/1000), byte('0'+(yy
/100)%10
), byte('0'+(yy
/10)%10
), byte('0'+yy%10
), ' ',
928 byte('0'+hh
/10), byte('0'+hh%10
), ':',
929 byte('0'+mn
/10), byte('0'+mn%10
), ':',
930 byte('0'+ss
/10), byte('0'+ss%10
), ' ',
934 var errTooLarge
= errors
.New("http: request too large")
936 // Read next request from connection.
937 func (c
*conn
) readRequest(ctx context
.Context
) (w
*response
, err error
) {
939 return nil, ErrHijacked
943 wholeReqDeadline time
.Time
// or zero if none
944 hdrDeadline time
.Time
// or zero if none
947 if d
:= c
.server
.readHeaderTimeout(); d
!= 0 {
948 hdrDeadline
= t0
.Add(d
)
950 if d
:= c
.server
.ReadTimeout
; d
!= 0 {
951 wholeReqDeadline
= t0
.Add(d
)
953 c
.rwc
.SetReadDeadline(hdrDeadline
)
954 if d
:= c
.server
.WriteTimeout
; d
!= 0 {
956 c
.rwc
.SetWriteDeadline(time
.Now().Add(d
))
960 c
.r
.setReadLimit(c
.server
.initialReadLimitSize())
961 if c
.lastMethod
== "POST" {
962 // RFC 7230 section 3 tolerance for old buggy clients.
963 peek
, _
:= c
.bufr
.Peek(4) // ReadRequest will get err below
964 c
.bufr
.Discard(numLeadingCRorLF(peek
))
966 req
, err
:= readRequest(c
.bufr
, keepHostHeader
)
968 if c
.r
.hitReadLimit() {
969 return nil, errTooLarge
974 if !http1ServerSupportsRequest(req
) {
975 return nil, badRequestError("unsupported protocol version")
978 c
.lastMethod
= req
.Method
979 c
.r
.setInfiniteReadLimit()
981 hosts
, haveHost
:= req
.Header
["Host"]
982 isH2Upgrade
:= req
.isH2Upgrade()
983 if req
.ProtoAtLeast(1, 1) && (!haveHost ||
len(hosts
) == 0) && !isH2Upgrade
&& req
.Method
!= "CONNECT" {
984 return nil, badRequestError("missing required Host header")
987 return nil, badRequestError("too many Host headers")
989 if len(hosts
) == 1 && !httpguts
.ValidHostHeader(hosts
[0]) {
990 return nil, badRequestError("malformed Host header")
992 for k
, vv
:= range req
.Header
{
993 if !httpguts
.ValidHeaderFieldName(k
) {
994 return nil, badRequestError("invalid header name")
996 for _
, v
:= range vv
{
997 if !httpguts
.ValidHeaderFieldValue(v
) {
998 return nil, badRequestError("invalid header value")
1002 delete(req
.Header
, "Host")
1004 ctx
, cancelCtx
:= context
.WithCancel(ctx
)
1006 req
.RemoteAddr
= c
.remoteAddr
1007 req
.TLS
= c
.tlsState
1008 if body
, ok
:= req
.Body
.(*body
); ok
{
1009 body
.doEarlyClose
= true
1012 // Adjust the read deadline if necessary.
1013 if !hdrDeadline
.Equal(wholeReqDeadline
) {
1014 c
.rwc
.SetReadDeadline(wholeReqDeadline
)
1019 cancelCtx
: cancelCtx
,
1022 handlerHeader
: make(Header
),
1024 closeNotifyCh
: make(chan bool, 1),
1026 // We populate these ahead of time so we're not
1027 // reading from req.Header after their Handler starts
1028 // and maybe mutates it (Issue 14940)
1029 wants10KeepAlive
: req
.wantsHttp10KeepAlive(),
1030 wantsClose
: req
.wantsClose(),
1033 w
.closeAfterReply
= true
1036 w
.w
= newBufioWriterSize(&w
.cw
, bufferBeforeChunkingSize
)
1040 // http1ServerSupportsRequest reports whether Go's HTTP/1.x server
1041 // supports the given request.
1042 func http1ServerSupportsRequest(req
*Request
) bool {
1043 if req
.ProtoMajor
== 1 {
1046 // Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
1047 // wire up their own HTTP/2 upgrades.
1048 if req
.ProtoMajor
== 2 && req
.ProtoMinor
== 0 &&
1049 req
.Method
== "PRI" && req
.RequestURI
== "*" {
1052 // Reject HTTP/0.x, and all other HTTP/2+ requests (which
1053 // aren't encoded in ASCII anyway).
1057 func (w
*response
) Header() Header
{
1058 if w
.cw
.header
== nil && w
.wroteHeader
&& !w
.cw
.wroteHeader
{
1059 // Accessing the header between logically writing it
1060 // and physically writing it means we need to allocate
1061 // a clone to snapshot the logically written state.
1062 w
.cw
.header
= w
.handlerHeader
.clone()
1064 w
.calledHeader
= true
1065 return w
.handlerHeader
1068 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
1069 // consumed by a handler that the server will read from the client
1070 // in order to keep a connection alive. If there are more bytes than
1071 // this then the server to be paranoid instead sends a "Connection:
1074 // This number is approximately what a typical machine's TCP buffer
1075 // size is anyway. (if we have the bytes on the machine, we might as
1077 const maxPostHandlerReadBytes
= 256 << 10
1079 func checkWriteHeaderCode(code
int) {
1080 // Issue 22880: require valid WriteHeader status codes.
1081 // For now we only enforce that it's three digits.
1082 // In the future we might block things over 599 (600 and above aren't defined
1083 // at https://httpwg.org/specs/rfc7231.html#status.codes)
1084 // and we might block under 200 (once we have more mature 1xx support).
1085 // But for now any three digits.
1087 // We used to send "HTTP/1.1 000 0" on the wire in responses but there's
1088 // no equivalent bogus thing we can realistically send in HTTP/2,
1089 // so we'll consistently panic instead and help people find their bugs
1090 // early. (We can't return an error from WriteHeader even if we wanted to.)
1091 if code
< 100 || code
> 999 {
1092 panic(fmt
.Sprintf("invalid WriteHeader code %v", code
))
1096 func (w
*response
) WriteHeader(code
int) {
1097 if w
.conn
.hijacked() {
1098 w
.conn
.server
.logf("http: response.WriteHeader on hijacked connection")
1102 w
.conn
.server
.logf("http: multiple response.WriteHeader calls")
1105 checkWriteHeaderCode(code
)
1106 w
.wroteHeader
= true
1109 if w
.calledHeader
&& w
.cw
.header
== nil {
1110 w
.cw
.header
= w
.handlerHeader
.clone()
1113 if cl
:= w
.handlerHeader
.get("Content-Length"); cl
!= "" {
1114 v
, err
:= strconv
.ParseInt(cl
, 10, 64)
1115 if err
== nil && v
>= 0 {
1118 w
.conn
.server
.logf("http: invalid Content-Length of %q", cl
)
1119 w
.handlerHeader
.Del("Content-Length")
1124 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
1125 // This type is used to avoid extra allocations from cloning and/or populating
1126 // the response Header map and all its 1-element slices.
1127 type extraHeader
struct {
1130 transferEncoding
string
1131 date
[]byte // written if not nil
1132 contentLength
[]byte // written if not nil
1135 // Sorted the same as extraHeader.Write's loop.
1136 var extraHeaderKeys
= [][]byte{
1137 []byte("Content-Type"),
1138 []byte("Connection"),
1139 []byte("Transfer-Encoding"),
1143 headerContentLength
= []byte("Content-Length: ")
1144 headerDate
= []byte("Date: ")
1147 // Write writes the headers described in h to w.
1149 // This method has a value receiver, despite the somewhat large size
1150 // of h, because it prevents an allocation. The escape analysis isn't
1151 // smart enough to realize this function doesn't mutate h.
1152 func (h extraHeader
) Write(w
*bufio
.Writer
) {
1158 if h
.contentLength
!= nil {
1159 w
.Write(headerContentLength
)
1160 w
.Write(h
.contentLength
)
1163 for i
, v
:= range []string{h
.contentType
, h
.connection
, h
.transferEncoding
} {
1165 w
.Write(extraHeaderKeys
[i
])
1173 // writeHeader finalizes the header sent to the client and writes it
1174 // to cw.res.conn.bufw.
1176 // p is not written by writeHeader, but is the first chunk of the body
1177 // that will be written. It is sniffed for a Content-Type if none is
1178 // set explicitly. It's also used to set the Content-Length, if the
1179 // total body size was small and the handler has already finished
1181 func (cw
*chunkWriter
) writeHeader(p
[]byte) {
1185 cw
.wroteHeader
= true
1188 keepAlivesEnabled
:= w
.conn
.server
.doKeepAlives()
1189 isHEAD
:= w
.req
.Method
== "HEAD"
1191 // header is written out to w.conn.buf below. Depending on the
1192 // state of the handler, we either own the map or not. If we
1193 // don't own it, the exclude map is created lazily for
1194 // WriteSubset to remove headers. The setHeader struct holds
1195 // headers we need to add.
1197 owned
:= header
!= nil
1199 header
= w
.handlerHeader
1201 var excludeHeader
map[string]bool
1202 delHeader
:= func(key
string) {
1207 if _
, ok
:= header
[key
]; !ok
{
1210 if excludeHeader
== nil {
1211 excludeHeader
= make(map[string]bool)
1213 excludeHeader
[key
] = true
1215 var setHeader extraHeader
1217 // Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
1219 for k
:= range cw
.header
{
1220 if strings
.HasPrefix(k
, TrailerPrefix
) {
1221 if excludeHeader
== nil {
1222 excludeHeader
= make(map[string]bool)
1224 excludeHeader
[k
] = true
1228 for _
, v
:= range cw
.header
["Trailer"] {
1230 foreachHeaderElement(v
, cw
.res
.declareTrailer
)
1233 te
:= header
.get("Transfer-Encoding")
1236 // If the handler is done but never sent a Content-Length
1237 // response header and this is our first (and last) write, set
1238 // it, even to zero. This helps HTTP/1.0 clients keep their
1239 // "keep-alive" connections alive.
1240 // Exceptions: 304/204/1xx responses never get Content-Length, and if
1241 // it was a HEAD request, we don't know the difference between
1242 // 0 actual bytes and 0 bytes because the handler noticed it
1243 // was a HEAD request and chose not to write anything. So for
1244 // HEAD, the handler should either write the Content-Length or
1245 // write non-zero bytes. If it's actually 0 bytes and the
1246 // handler never looked at the Request.Method, we just don't
1247 // send a Content-Length header.
1248 // Further, we don't send an automatic Content-Length if they
1249 // set a Transfer-Encoding, because they're generally incompatible.
1250 if w
.handlerDone
.isSet() && !trailers
&& !hasTE
&& bodyAllowedForStatus(w
.status
) && header
.get("Content-Length") == "" && (!isHEAD ||
len(p
) > 0) {
1251 w
.contentLength
= int64(len(p
))
1252 setHeader
.contentLength
= strconv
.AppendInt(cw
.res
.clenBuf
[:0], int64(len(p
)), 10)
1255 // If this was an HTTP/1.0 request with keep-alive and we sent a
1256 // Content-Length back, we can make this a keep-alive response ...
1257 if w
.wants10KeepAlive
&& keepAlivesEnabled
{
1258 sentLength
:= header
.get("Content-Length") != ""
1259 if sentLength
&& header
.get("Connection") == "keep-alive" {
1260 w
.closeAfterReply
= false
1264 // Check for an explicit (and valid) Content-Length header.
1265 hasCL
:= w
.contentLength
!= -1
1267 if w
.wants10KeepAlive
&& (isHEAD || hasCL ||
!bodyAllowedForStatus(w
.status
)) {
1268 _
, connectionHeaderSet
:= header
["Connection"]
1269 if !connectionHeaderSet
{
1270 setHeader
.connection
= "keep-alive"
1272 } else if !w
.req
.ProtoAtLeast(1, 1) || w
.wantsClose
{
1273 w
.closeAfterReply
= true
1276 if header
.get("Connection") == "close" ||
!keepAlivesEnabled
{
1277 w
.closeAfterReply
= true
1280 // If the client wanted a 100-continue but we never sent it to
1281 // them (or, more strictly: we never finished reading their
1282 // request body), don't reuse this connection because it's now
1283 // in an unknown state: we might be sending this response at
1284 // the same time the client is now sending its request body
1285 // after a timeout. (Some HTTP clients send Expect:
1286 // 100-continue but knowing that some servers don't support
1287 // it, the clients set a timer and send the body later anyway)
1288 // If we haven't seen EOF, we can't skip over the unread body
1289 // because we don't know if the next bytes on the wire will be
1290 // the body-following-the-timer or the subsequent request.
1292 if ecr
, ok
:= w
.req
.Body
.(*expectContinueReader
); ok
&& !ecr
.sawEOF
{
1293 w
.closeAfterReply
= true
1296 // Per RFC 2616, we should consume the request body before
1297 // replying, if the handler hasn't already done so. But we
1298 // don't want to do an unbounded amount of reading here for
1299 // DoS reasons, so we only try up to a threshold.
1300 // TODO(bradfitz): where does RFC 2616 say that? See Issue 15527
1301 // about HTTP/1.x Handlers concurrently reading and writing, like
1302 // HTTP/2 handlers can do. Maybe this code should be relaxed?
1303 if w
.req
.ContentLength
!= 0 && !w
.closeAfterReply
{
1304 var discard
, tooBig
bool
1306 switch bdy
:= w
.req
.Body
.(type) {
1307 case *expectContinueReader
:
1308 if bdy
.resp
.wroteContinue
{
1316 // Body was closed in handler with non-EOF error.
1317 w
.closeAfterReply
= true
1319 case bdy
.unreadDataSizeLocked() >= maxPostHandlerReadBytes
:
1330 _
, err
:= io
.CopyN(ioutil
.Discard
, w
.reqBody
, maxPostHandlerReadBytes
+1)
1333 // There must be even more data left over.
1335 case ErrBodyReadAfterClose
:
1336 // Body was already consumed and closed.
1338 // The remaining body was just consumed, close it.
1339 err
= w
.reqBody
.Close()
1341 w
.closeAfterReply
= true
1344 // Some other kind of error occurred, like a read timeout, or
1345 // corrupt chunked encoding. In any case, whatever remains
1346 // on the wire must not be parsed as another HTTP request.
1347 w
.closeAfterReply
= true
1353 delHeader("Connection")
1354 setHeader
.connection
= "close"
1359 if bodyAllowedForStatus(code
) {
1360 // If no content type, apply sniffing algorithm to body.
1361 _
, haveType
:= header
["Content-Type"]
1362 if !haveType
&& !hasTE
&& len(p
) > 0 {
1363 setHeader
.contentType
= DetectContentType(p
)
1366 for _
, k
:= range suppressedHeaders(code
) {
1371 if _
, ok
:= header
["Date"]; !ok
{
1372 setHeader
.date
= appendTime(cw
.res
.dateBuf
[:0], time
.Now())
1375 if hasCL
&& hasTE
&& te
!= "identity" {
1376 // TODO: return an error if WriteHeader gets a return parameter
1377 // For now just ignore the Content-Length.
1378 w
.conn
.server
.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
1379 te
, w
.contentLength
)
1380 delHeader("Content-Length")
1384 if w
.req
.Method
== "HEAD" ||
!bodyAllowedForStatus(code
) {
1386 } else if code
== StatusNoContent
{
1387 delHeader("Transfer-Encoding")
1389 delHeader("Transfer-Encoding")
1390 } else if w
.req
.ProtoAtLeast(1, 1) {
1391 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
1392 // content-length has been provided. The connection must be closed after the
1393 // reply is written, and no chunking is to be done. This is the setup
1394 // recommended in the Server-Sent Events candidate recommendation 11,
1396 if hasTE
&& te
== "identity" {
1398 w
.closeAfterReply
= true
1400 // HTTP/1.1 or greater: use chunked transfer encoding
1401 // to avoid closing the connection at EOF.
1403 setHeader
.transferEncoding
= "chunked"
1404 if hasTE
&& te
== "chunked" {
1405 // We will send the chunked Transfer-Encoding header later.
1406 delHeader("Transfer-Encoding")
1410 // HTTP version < 1.1: cannot do chunked transfer
1411 // encoding and we don't know the Content-Length so
1412 // signal EOF by closing connection.
1413 w
.closeAfterReply
= true
1414 delHeader("Transfer-Encoding") // in case already set
1417 // Cannot use Content-Length with non-identity Transfer-Encoding.
1419 delHeader("Content-Length")
1421 if !w
.req
.ProtoAtLeast(1, 0) {
1425 if w
.closeAfterReply
&& (!keepAlivesEnabled ||
!hasToken(cw
.header
.get("Connection"), "close")) {
1426 delHeader("Connection")
1427 if w
.req
.ProtoAtLeast(1, 1) {
1428 setHeader
.connection
= "close"
1432 writeStatusLine(w
.conn
.bufw
, w
.req
.ProtoAtLeast(1, 1), code
, w
.statusBuf
[:])
1433 cw
.header
.WriteSubset(w
.conn
.bufw
, excludeHeader
)
1434 setHeader
.Write(w
.conn
.bufw
)
1435 w
.conn
.bufw
.Write(crlf
)
1438 // foreachHeaderElement splits v according to the "#rule" construction
1439 // in RFC 7230 section 7 and calls fn for each non-empty element.
1440 func foreachHeaderElement(v
string, fn
func(string)) {
1441 v
= textproto
.TrimString(v
)
1445 if !strings
.Contains(v
, ",") {
1449 for _
, f
:= range strings
.Split(v
, ",") {
1450 if f
= textproto
.TrimString(f
); f
!= "" {
1456 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
1457 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
1458 // code is the response status code.
1459 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
1460 func writeStatusLine(bw
*bufio
.Writer
, is11
bool, code
int, scratch
[]byte) {
1462 bw
.WriteString("HTTP/1.1 ")
1464 bw
.WriteString("HTTP/1.0 ")
1466 if text
, ok
:= statusText
[code
]; ok
{
1467 bw
.Write(strconv
.AppendInt(scratch
[:0], int64(code
), 10))
1469 bw
.WriteString(text
)
1470 bw
.WriteString("\r\n")
1472 // don't worry about performance
1473 fmt
.Fprintf(bw
, "%03d status code %d\r\n", code
, code
)
1477 // bodyAllowed reports whether a Write is allowed for this response type.
1478 // It's illegal to call this before the header has been flushed.
1479 func (w
*response
) bodyAllowed() bool {
1483 return bodyAllowedForStatus(w
.status
)
1486 // The Life Of A Write is like this:
1488 // Handler starts. No header has been sent. The handler can either
1489 // write a header, or just start writing. Writing before sending a header
1490 // sends an implicitly empty 200 OK header.
1492 // If the handler didn't declare a Content-Length up front, we either
1493 // go into chunking mode or, if the handler finishes running before
1494 // the chunking buffer size, we compute a Content-Length and send that
1495 // in the header instead.
1497 // Likewise, if the handler didn't set a Content-Type, we sniff that
1498 // from the initial chunk of output.
1500 // The Writers are wired together like:
1502 // 1. *response (the ResponseWriter) ->
1503 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
1504 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
1505 // and which writes the chunk headers, if needed.
1506 // 4. conn.buf, a bufio.Writer of default (4kB) bytes, writing to ->
1507 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
1508 // and populates c.werr with it if so. but otherwise writes to:
1509 // 6. the rwc, the net.Conn.
1511 // TODO(bradfitz): short-circuit some of the buffering when the
1512 // initial header contains both a Content-Type and Content-Length.
1513 // Also short-circuit in (1) when the header's been sent and not in
1514 // chunking mode, writing directly to (4) instead, if (2) has no
1515 // buffered data. More generally, we could short-circuit from (1) to
1516 // (3) even in chunking mode if the write size from (1) is over some
1517 // threshold and nothing is in (2). The answer might be mostly making
1518 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
1519 // with this instead.
1520 func (w
*response
) Write(data
[]byte) (n
int, err error
) {
1521 return w
.write(len(data
), data
, "")
1524 func (w
*response
) WriteString(data
string) (n
int, err error
) {
1525 return w
.write(len(data
), nil, data
)
1528 // either dataB or dataS is non-zero.
1529 func (w
*response
) write(lenData
int, dataB
[]byte, dataS
string) (n
int, err error
) {
1530 if w
.conn
.hijacked() {
1532 w
.conn
.server
.logf("http: response.Write on hijacked connection")
1534 return 0, ErrHijacked
1537 w
.WriteHeader(StatusOK
)
1542 if !w
.bodyAllowed() {
1543 return 0, ErrBodyNotAllowed
1546 w
.written
+= int64(lenData
) // ignoring errors, for errorKludge
1547 if w
.contentLength
!= -1 && w
.written
> w
.contentLength
{
1548 return 0, ErrContentLength
1551 return w
.w
.Write(dataB
)
1553 return w
.w
.WriteString(dataS
)
1557 func (w
*response
) finishRequest() {
1558 w
.handlerDone
.setTrue()
1561 w
.WriteHeader(StatusOK
)
1569 w
.conn
.r
.abortPendingRead()
1571 // Close the body (regardless of w.closeAfterReply) so we can
1572 // re-use its bufio.Reader later safely.
1575 if w
.req
.MultipartForm
!= nil {
1576 w
.req
.MultipartForm
.RemoveAll()
1580 // shouldReuseConnection reports whether the underlying TCP connection can be reused.
1581 // It must only be called after the handler is done executing.
1582 func (w
*response
) shouldReuseConnection() bool {
1583 if w
.closeAfterReply
{
1584 // The request or something set while executing the
1585 // handler indicated we shouldn't reuse this
1590 if w
.req
.Method
!= "HEAD" && w
.contentLength
!= -1 && w
.bodyAllowed() && w
.contentLength
!= w
.written
{
1591 // Did not write enough. Avoid getting out of sync.
1595 // There was some error writing to the underlying connection
1596 // during the request, so don't re-use this conn.
1597 if w
.conn
.werr
!= nil {
1601 if w
.closedRequestBodyEarly() {
1608 func (w
*response
) closedRequestBodyEarly() bool {
1609 body
, ok
:= w
.req
.Body
.(*body
)
1610 return ok
&& body
.didEarlyClose()
1613 func (w
*response
) Flush() {
1615 w
.WriteHeader(StatusOK
)
1621 func (c
*conn
) finalFlush() {
1623 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1624 // reader for a future connection.
1625 putBufioReader(c
.bufr
)
1631 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1632 // writer for a future connection.
1633 putBufioWriter(c
.bufw
)
1638 // Close the connection.
1639 func (c
*conn
) close() {
1644 // rstAvoidanceDelay is the amount of time we sleep after closing the
1645 // write side of a TCP connection before closing the entire socket.
1646 // By sleeping, we increase the chances that the client sees our FIN
1647 // and processes its final data before they process the subsequent RST
1648 // from closing a connection with known unread data.
1649 // This RST seems to occur mostly on BSD systems. (And Windows?)
1650 // This timeout is somewhat arbitrary (~latency around the planet).
1651 const rstAvoidanceDelay
= 500 * time
.Millisecond
1653 type closeWriter
interface {
1657 var _ closeWriter
= (*net
.TCPConn
)(nil)
1659 // closeWrite flushes any outstanding data and sends a FIN packet (if
1660 // client is connected via TCP), signalling that we're done. We then
1661 // pause for a bit, hoping the client processes it before any
1664 // See https://golang.org/issue/3595
1665 func (c
*conn
) closeWriteAndWait() {
1667 if tcp
, ok
:= c
.rwc
.(closeWriter
); ok
{
1670 time
.Sleep(rstAvoidanceDelay
)
1673 // validNPN reports whether the proto is not a blacklisted Next
1674 // Protocol Negotiation protocol. Empty and built-in protocol types
1675 // are blacklisted and can't be overridden with alternate
1677 func validNPN(proto
string) bool {
1679 case "", "http/1.1", "http/1.0":
1685 func (c
*conn
) setState(nc net
.Conn
, state ConnState
) {
1689 srv
.trackConn(c
, true)
1690 case StateHijacked
, StateClosed
:
1691 srv
.trackConn(c
, false)
1693 if state
> 0xff || state
< 0 {
1694 panic("internal error")
1696 packedState
:= uint64(time
.Now().Unix()<<8) |
uint64(state
)
1697 atomic
.StoreUint64(&c
.curState
.atomic
, packedState
)
1698 if hook
:= srv
.ConnState
; hook
!= nil {
1703 func (c
*conn
) getState() (state ConnState
, unixSec
int64) {
1704 packedState
:= atomic
.LoadUint64(&c
.curState
.atomic
)
1705 return ConnState(packedState
& 0xff), int64(packedState
>> 8)
1708 // badRequestError is a literal string (used by in the server in HTML,
1709 // unescaped) to tell the user why their request was bad. It should
1710 // be plain text without user info or other embedded errors.
1711 type badRequestError
string
1713 func (e badRequestError
) Error() string { return "Bad Request: " + string(e
) }
1715 // ErrAbortHandler is a sentinel panic value to abort a handler.
1716 // While any panic from ServeHTTP aborts the response to the client,
1717 // panicking with ErrAbortHandler also suppresses logging of a stack
1718 // trace to the server's error log.
1719 var ErrAbortHandler
= errors
.New("net/http: abort Handler")
1721 // isCommonNetReadError reports whether err is a common error
1722 // encountered during reading a request off the network when the
1723 // client has gone away or had its read fail somehow. This is used to
1724 // determine which logs are interesting enough to log about.
1725 func isCommonNetReadError(err error
) bool {
1729 if neterr
, ok
:= err
.(net
.Error
); ok
&& neterr
.Timeout() {
1732 if oe
, ok
:= err
.(*net
.OpError
); ok
&& oe
.Op
== "read" {
1738 // Serve a new connection.
1739 func (c
*conn
) serve(ctx context
.Context
) {
1740 c
.remoteAddr
= c
.rwc
.RemoteAddr().String()
1741 ctx
= context
.WithValue(ctx
, LocalAddrContextKey
, c
.rwc
.LocalAddr())
1743 if err
:= recover(); err
!= nil && err
!= ErrAbortHandler
{
1744 const size
= 64 << 10
1745 buf
:= make([]byte, size
)
1746 buf
= buf
[:runtime
.Stack(buf
, false)]
1747 c
.server
.logf("http: panic serving %v: %v\n%s", c
.remoteAddr
, err
, buf
)
1751 c
.setState(c
.rwc
, StateClosed
)
1755 if tlsConn
, ok
:= c
.rwc
.(*tls
.Conn
); ok
{
1756 if d
:= c
.server
.ReadTimeout
; d
!= 0 {
1757 c
.rwc
.SetReadDeadline(time
.Now().Add(d
))
1759 if d
:= c
.server
.WriteTimeout
; d
!= 0 {
1760 c
.rwc
.SetWriteDeadline(time
.Now().Add(d
))
1762 if err
:= tlsConn
.Handshake(); err
!= nil {
1763 c
.server
.logf("http: TLS handshake error from %s: %v", c
.rwc
.RemoteAddr(), err
)
1766 c
.tlsState
= new(tls
.ConnectionState
)
1767 *c
.tlsState
= tlsConn
.ConnectionState()
1768 if proto
:= c
.tlsState
.NegotiatedProtocol
; validNPN(proto
) {
1769 if fn
:= c
.server
.TLSNextProto
[proto
]; fn
!= nil {
1770 h
:= initNPNRequest
{tlsConn
, serverHandler
{c
.server
}}
1771 fn(c
.server
, tlsConn
, h
)
1777 // HTTP/1.x from here on.
1779 ctx
, cancelCtx
:= context
.WithCancel(ctx
)
1780 c
.cancelCtx
= cancelCtx
1783 c
.r
= &connReader
{conn
: c
}
1784 c
.bufr
= newBufioReader(c
.r
)
1785 c
.bufw
= newBufioWriterSize(checkConnErrorWriter
{c
}, 4<<10)
1788 w
, err
:= c
.readRequest(ctx
)
1789 if c
.r
.remain
!= c
.server
.initialReadLimitSize() {
1790 // If we read any bytes off the wire, we're active.
1791 c
.setState(c
.rwc
, StateActive
)
1794 const errorHeaders
= "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
1796 if err
== errTooLarge
{
1797 // Their HTTP client may or may not be
1798 // able to read this if we're
1799 // responding to them and hanging up
1800 // while they're still writing their
1801 // request. Undefined behavior.
1802 const publicErr
= "431 Request Header Fields Too Large"
1803 fmt
.Fprintf(c
.rwc
, "HTTP/1.1 "+publicErr
+errorHeaders
+publicErr
)
1804 c
.closeWriteAndWait()
1807 if isCommonNetReadError(err
) {
1808 return // don't reply
1811 publicErr
:= "400 Bad Request"
1812 if v
, ok
:= err
.(badRequestError
); ok
{
1813 publicErr
= publicErr
+ ": " + string(v
)
1816 fmt
.Fprintf(c
.rwc
, "HTTP/1.1 "+publicErr
+errorHeaders
+publicErr
)
1820 // Expect 100 Continue support
1822 if req
.expectsContinue() {
1823 if req
.ProtoAtLeast(1, 1) && req
.ContentLength
!= 0 {
1824 // Wrap the Body reader with one that replies on the connection
1825 req
.Body
= &expectContinueReader
{readCloser
: req
.Body
, resp
: w
}
1827 } else if req
.Header
.get("Expect") != "" {
1828 w
.sendExpectationFailed()
1834 if requestBodyRemains(req
.Body
) {
1835 registerOnHitEOF(req
.Body
, w
.conn
.r
.startBackgroundRead
)
1837 w
.conn
.r
.startBackgroundRead()
1840 // HTTP cannot have multiple simultaneous active requests.[*]
1841 // Until the server replies to this request, it can't read another,
1842 // so we might as well run the handler in this goroutine.
1843 // [*] Not strictly true: HTTP pipelining. We could let them all process
1844 // in parallel even if their responses need to be serialized.
1845 // But we're not going to implement HTTP pipelining because it
1846 // was never deployed in the wild and the answer is HTTP/2.
1847 serverHandler
{c
.server
}.ServeHTTP(w
, w
.req
)
1853 if !w
.shouldReuseConnection() {
1854 if w
.requestBodyLimitHit || w
.closedRequestBodyEarly() {
1855 c
.closeWriteAndWait()
1859 c
.setState(c
.rwc
, StateIdle
)
1860 c
.curReq
.Store((*response
)(nil))
1862 if !w
.conn
.server
.doKeepAlives() {
1863 // We're in shutdown mode. We might've replied
1864 // to the user without "Connection: close" and
1865 // they might think they can send another
1866 // request, but such is life with HTTP/1.1.
1870 if d
:= c
.server
.idleTimeout(); d
!= 0 {
1871 c
.rwc
.SetReadDeadline(time
.Now().Add(d
))
1872 if _
, err
:= c
.bufr
.Peek(4); err
!= nil {
1876 c
.rwc
.SetReadDeadline(time
.Time
{})
1880 func (w
*response
) sendExpectationFailed() {
1881 // TODO(bradfitz): let ServeHTTP handlers handle
1882 // requests with non-standard expectation[s]? Seems
1883 // theoretical at best, and doesn't fit into the
1884 // current ServeHTTP model anyway. We'd need to
1885 // make the ResponseWriter an optional
1886 // "ExpectReplier" interface or something.
1888 // For now we'll just obey RFC 7231 5.1.1 which says
1889 // "A server that receives an Expect field-value other
1890 // than 100-continue MAY respond with a 417 (Expectation
1891 // Failed) status code to indicate that the unexpected
1892 // expectation cannot be met."
1893 w
.Header().Set("Connection", "close")
1894 w
.WriteHeader(StatusExpectationFailed
)
1898 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
1900 func (w
*response
) Hijack() (rwc net
.Conn
, buf
*bufio
.ReadWriter
, err error
) {
1901 if w
.handlerDone
.isSet() {
1902 panic("net/http: Hijack called after ServeHTTP finished")
1912 // Release the bufioWriter that writes to the chunk writer, it is not
1913 // used after a connection has been hijacked.
1914 rwc
, buf
, err
= c
.hijackLocked()
1919 return rwc
, buf
, err
1922 func (w
*response
) CloseNotify() <-chan bool {
1923 if w
.handlerDone
.isSet() {
1924 panic("net/http: CloseNotify called after ServeHTTP finished")
1926 return w
.closeNotifyCh
1929 func registerOnHitEOF(rc io
.ReadCloser
, fn
func()) {
1930 switch v
:= rc
.(type) {
1931 case *expectContinueReader
:
1932 registerOnHitEOF(v
.readCloser
, fn
)
1934 v
.registerOnHitEOF(fn
)
1936 panic("unexpected type " + fmt
.Sprintf("%T", rc
))
1940 // requestBodyRemains reports whether future calls to Read
1941 // on rc might yield more data.
1942 func requestBodyRemains(rc io
.ReadCloser
) bool {
1946 switch v
:= rc
.(type) {
1947 case *expectContinueReader
:
1948 return requestBodyRemains(v
.readCloser
)
1950 return v
.bodyRemains()
1952 panic("unexpected type " + fmt
.Sprintf("%T", rc
))
1956 // The HandlerFunc type is an adapter to allow the use of
1957 // ordinary functions as HTTP handlers. If f is a function
1958 // with the appropriate signature, HandlerFunc(f) is a
1959 // Handler that calls f.
1960 type HandlerFunc
func(ResponseWriter
, *Request
)
1962 // ServeHTTP calls f(w, r).
1963 func (f HandlerFunc
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1969 // Error replies to the request with the specified error message and HTTP code.
1970 // It does not otherwise end the request; the caller should ensure no further
1971 // writes are done to w.
1972 // The error message should be plain text.
1973 func Error(w ResponseWriter
, error
string, code
int) {
1974 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
1975 w
.Header().Set("X-Content-Type-Options", "nosniff")
1977 fmt
.Fprintln(w
, error
)
1980 // NotFound replies to the request with an HTTP 404 not found error.
1981 func NotFound(w ResponseWriter
, r
*Request
) { Error(w
, "404 page not found", StatusNotFound
) }
1983 // NotFoundHandler returns a simple request handler
1984 // that replies to each request with a ``404 page not found'' reply.
1985 func NotFoundHandler() Handler
{ return HandlerFunc(NotFound
) }
1987 // StripPrefix returns a handler that serves HTTP requests
1988 // by removing the given prefix from the request URL's Path
1989 // and invoking the handler h. StripPrefix handles a
1990 // request for a path that doesn't begin with prefix by
1991 // replying with an HTTP 404 not found error.
1992 func StripPrefix(prefix
string, h Handler
) Handler
{
1996 return HandlerFunc(func(w ResponseWriter
, r
*Request
) {
1997 if p
:= strings
.TrimPrefix(r
.URL
.Path
, prefix
); len(p
) < len(r
.URL
.Path
) {
2000 r2
.URL
= new(url
.URL
)
2010 // Redirect replies to the request with a redirect to url,
2011 // which may be a path relative to the request path.
2013 // The provided code should be in the 3xx range and is usually
2014 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2016 // If the Content-Type header has not been set, Redirect sets it
2017 // to "text/html; charset=utf-8" and writes a small HTML body.
2018 // Setting the Content-Type header to any value, including nil,
2019 // disables that behavior.
2020 func Redirect(w ResponseWriter
, r
*Request
, url
string, code
int) {
2021 // parseURL is just url.Parse (url is shadowed for godoc).
2022 if u
, err
:= parseURL(url
); err
== nil {
2023 // If url was relative, make its path absolute by
2024 // combining with request path.
2025 // The client would probably do this for us,
2026 // but doing it ourselves is more reliable.
2027 // See RFC 7231, section 7.1.2
2028 if u
.Scheme
== "" && u
.Host
== "" {
2029 oldpath
:= r
.URL
.Path
2030 if oldpath
== "" { // should not happen, but avoid a crash if it does
2034 // no leading http://server
2035 if url
== "" || url
[0] != '/' {
2036 // make relative path absolute
2037 olddir
, _
:= path
.Split(oldpath
)
2042 if i
:= strings
.Index(url
, "?"); i
!= -1 {
2043 url
, query
= url
[:i
], url
[i
:]
2046 // clean up but preserve trailing slash
2047 trailing
:= strings
.HasSuffix(url
, "/")
2048 url
= path
.Clean(url
)
2049 if trailing
&& !strings
.HasSuffix(url
, "/") {
2058 // RFC 7231 notes that a short HTML body is usually included in
2059 // the response because older user agents may not understand 301/307.
2060 // Do it only if the request didn't already have a Content-Type header.
2061 _
, hadCT
:= h
["Content-Type"]
2063 h
.Set("Location", hexEscapeNonASCII(url
))
2064 if !hadCT
&& (r
.Method
== "GET" || r
.Method
== "HEAD") {
2065 h
.Set("Content-Type", "text/html; charset=utf-8")
2069 // Shouldn't send the body for POST or HEAD; that leaves GET.
2070 if !hadCT
&& r
.Method
== "GET" {
2071 body
:= "<a href=\"" + htmlEscape(url
) + "\">" + statusText
[code
] + "</a>.\n"
2072 fmt
.Fprintln(w
, body
)
2076 // parseURL is just url.Parse. It exists only so that url.Parse can be called
2077 // in places where url is shadowed for godoc. See https://golang.org/cl/49930.
2078 var parseURL
= url
.Parse
2080 var htmlReplacer
= strings
.NewReplacer(
2084 // """ is shorter than """.
2086 // "'" is shorter than "'" and apos was not in HTML until HTML5.
2090 func htmlEscape(s
string) string {
2091 return htmlReplacer
.Replace(s
)
2094 // Redirect to a fixed URL
2095 type redirectHandler
struct {
2100 func (rh
*redirectHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
2101 Redirect(w
, r
, rh
.url
, rh
.code
)
2104 // RedirectHandler returns a request handler that redirects
2105 // each request it receives to the given url using the given
2108 // The provided code should be in the 3xx range and is usually
2109 // StatusMovedPermanently, StatusFound or StatusSeeOther.
2110 func RedirectHandler(url
string, code
int) Handler
{
2111 return &redirectHandler
{url
, code
}
2114 // ServeMux is an HTTP request multiplexer.
2115 // It matches the URL of each incoming request against a list of registered
2116 // patterns and calls the handler for the pattern that
2117 // most closely matches the URL.
2119 // Patterns name fixed, rooted paths, like "/favicon.ico",
2120 // or rooted subtrees, like "/images/" (note the trailing slash).
2121 // Longer patterns take precedence over shorter ones, so that
2122 // if there are handlers registered for both "/images/"
2123 // and "/images/thumbnails/", the latter handler will be
2124 // called for paths beginning "/images/thumbnails/" and the
2125 // former will receive requests for any other paths in the
2126 // "/images/" subtree.
2128 // Note that since a pattern ending in a slash names a rooted subtree,
2129 // the pattern "/" matches all paths not matched by other registered
2130 // patterns, not just the URL with Path == "/".
2132 // If a subtree has been registered and a request is received naming the
2133 // subtree root without its trailing slash, ServeMux redirects that
2134 // request to the subtree root (adding the trailing slash). This behavior can
2135 // be overridden with a separate registration for the path without
2136 // the trailing slash. For example, registering "/images/" causes ServeMux
2137 // to redirect a request for "/images" to "/images/", unless "/images" has
2138 // been registered separately.
2140 // Patterns may optionally begin with a host name, restricting matches to
2141 // URLs on that host only. Host-specific patterns take precedence over
2142 // general patterns, so that a handler might register for the two patterns
2143 // "/codesearch" and "codesearch.google.com/" without also taking over
2144 // requests for "http://www.google.com/".
2146 // ServeMux also takes care of sanitizing the URL request path and the Host
2147 // header, stripping the port number and redirecting any request containing . or
2148 // .. elements or repeated slashes to an equivalent, cleaner URL.
2149 type ServeMux
struct {
2151 m
map[string]muxEntry
2152 hosts
bool // whether any patterns contain hostnames
2155 type muxEntry
struct {
2160 // NewServeMux allocates and returns a new ServeMux.
2161 func NewServeMux() *ServeMux
{ return new(ServeMux
) }
2163 // DefaultServeMux is the default ServeMux used by Serve.
2164 var DefaultServeMux
= &defaultServeMux
2166 var defaultServeMux ServeMux
2168 // Does path match pattern?
2169 func pathMatch(pattern
, path
string) bool {
2170 if len(pattern
) == 0 {
2171 // should not happen
2175 if pattern
[n
-1] != '/' {
2176 return pattern
== path
2178 return len(path
) >= n
&& path
[0:n
] == pattern
2181 // cleanPath returns the canonical path for p, eliminating . and .. elements.
2182 func cleanPath(p
string) string {
2190 // path.Clean removes trailing slash except for root;
2191 // put the trailing slash back if necessary.
2192 if p
[len(p
)-1] == '/' && np
!= "/" {
2193 // Fast path for common case of p being the string we want:
2194 if len(p
) == len(np
)+1 && strings
.HasPrefix(p
, np
) {
2203 // stripHostPort returns h without any trailing ":<port>".
2204 func stripHostPort(h
string) string {
2205 // If no port on host, return unchanged
2206 if strings
.IndexByte(h
, ':') == -1 {
2209 host
, _
, err
:= net
.SplitHostPort(h
)
2211 return h
// on error, return unchanged
2216 // Find a handler on a handler map given a path string.
2217 // Most-specific (longest) pattern wins.
2218 func (mux
*ServeMux
) match(path
string) (h Handler
, pattern
string) {
2219 // Check for exact match first.
2220 v
, ok
:= mux
.m
[path
]
2222 return v
.h
, v
.pattern
2225 // Check for longest valid match.
2227 for k
, v
:= range mux
.m
{
2228 if !pathMatch(k
, path
) {
2231 if h
== nil ||
len(k
) > n
{
2240 // redirectToPathSlash determines if the given path needs appending "/" to it.
2241 // This occurs when a handler for path + "/" was already registered, but
2242 // not for path itself. If the path needs appending to, it creates a new
2243 // URL, setting the path to u.Path + "/" and returning true to indicate so.
2244 func (mux
*ServeMux
) redirectToPathSlash(host
, path
string, u
*url
.URL
) (*url
.URL
, bool) {
2246 shouldRedirect
:= mux
.shouldRedirectRLocked(host
, path
)
2248 if !shouldRedirect
{
2252 u
= &url
.URL
{Path
: path
, RawQuery
: u
.RawQuery
}
2256 // shouldRedirectRLocked reports whether the given path and host should be redirected to
2257 // path+"/". This should happen if a handler is registered for path+"/" but
2258 // not path -- see comments at ServeMux.
2259 func (mux
*ServeMux
) shouldRedirectRLocked(host
, path
string) bool {
2260 p
:= []string{path
, host
+ path
}
2262 for _
, c
:= range p
{
2263 if _
, exist
:= mux
.m
[c
]; exist
{
2272 for _
, c
:= range p
{
2273 if _
, exist
:= mux
.m
[c
+"/"]; exist
{
2274 return path
[n
-1] != '/'
2281 // Handler returns the handler to use for the given request,
2282 // consulting r.Method, r.Host, and r.URL.Path. It always returns
2283 // a non-nil handler. If the path is not in its canonical form, the
2284 // handler will be an internally-generated handler that redirects
2285 // to the canonical path. If the host contains a port, it is ignored
2286 // when matching handlers.
2288 // The path and host are used unchanged for CONNECT requests.
2290 // Handler also returns the registered pattern that matches the
2291 // request or, in the case of internally-generated redirects,
2292 // the pattern that will match after following the redirect.
2294 // If there is no registered handler that applies to the request,
2295 // Handler returns a ``page not found'' handler and an empty pattern.
2296 func (mux
*ServeMux
) Handler(r
*Request
) (h Handler
, pattern
string) {
2298 // CONNECT requests are not canonicalized.
2299 if r
.Method
== "CONNECT" {
2300 // If r.URL.Path is /tree and its handler is not registered,
2301 // the /tree -> /tree/ redirect applies to CONNECT requests
2302 // but the path canonicalization does not.
2303 if u
, ok
:= mux
.redirectToPathSlash(r
.URL
.Host
, r
.URL
.Path
, r
.URL
); ok
{
2304 return RedirectHandler(u
.String(), StatusMovedPermanently
), u
.Path
2307 return mux
.handler(r
.Host
, r
.URL
.Path
)
2310 // All other requests have any port stripped and path cleaned
2311 // before passing to mux.handler.
2312 host
:= stripHostPort(r
.Host
)
2313 path
:= cleanPath(r
.URL
.Path
)
2315 // If the given path is /tree and its handler is not registered,
2316 // redirect for /tree/.
2317 if u
, ok
:= mux
.redirectToPathSlash(host
, path
, r
.URL
); ok
{
2318 return RedirectHandler(u
.String(), StatusMovedPermanently
), u
.Path
2321 if path
!= r
.URL
.Path
{
2322 _
, pattern
= mux
.handler(host
, path
)
2325 return RedirectHandler(url
.String(), StatusMovedPermanently
), pattern
2328 return mux
.handler(host
, r
.URL
.Path
)
2331 // handler is the main implementation of Handler.
2332 // The path is known to be in canonical form, except for CONNECT methods.
2333 func (mux
*ServeMux
) handler(host
, path
string) (h Handler
, pattern
string) {
2335 defer mux
.mu
.RUnlock()
2337 // Host-specific pattern takes precedence over generic ones
2339 h
, pattern
= mux
.match(host
+ path
)
2342 h
, pattern
= mux
.match(path
)
2345 h
, pattern
= NotFoundHandler(), ""
2350 // ServeHTTP dispatches the request to the handler whose
2351 // pattern most closely matches the request URL.
2352 func (mux
*ServeMux
) ServeHTTP(w ResponseWriter
, r
*Request
) {
2353 if r
.RequestURI
== "*" {
2354 if r
.ProtoAtLeast(1, 1) {
2355 w
.Header().Set("Connection", "close")
2357 w
.WriteHeader(StatusBadRequest
)
2360 h
, _
:= mux
.Handler(r
)
2364 // Handle registers the handler for the given pattern.
2365 // If a handler already exists for pattern, Handle panics.
2366 func (mux
*ServeMux
) Handle(pattern
string, handler Handler
) {
2368 defer mux
.mu
.Unlock()
2371 panic("http: invalid pattern")
2374 panic("http: nil handler")
2376 if _
, exist
:= mux
.m
[pattern
]; exist
{
2377 panic("http: multiple registrations for " + pattern
)
2381 mux
.m
= make(map[string]muxEntry
)
2383 mux
.m
[pattern
] = muxEntry
{h
: handler
, pattern
: pattern
}
2385 if pattern
[0] != '/' {
2390 // HandleFunc registers the handler function for the given pattern.
2391 func (mux
*ServeMux
) HandleFunc(pattern
string, handler
func(ResponseWriter
, *Request
)) {
2393 panic("http: nil handler")
2395 mux
.Handle(pattern
, HandlerFunc(handler
))
2398 // Handle registers the handler for the given pattern
2399 // in the DefaultServeMux.
2400 // The documentation for ServeMux explains how patterns are matched.
2401 func Handle(pattern
string, handler Handler
) { DefaultServeMux
.Handle(pattern
, handler
) }
2403 // HandleFunc registers the handler function for the given pattern
2404 // in the DefaultServeMux.
2405 // The documentation for ServeMux explains how patterns are matched.
2406 func HandleFunc(pattern
string, handler
func(ResponseWriter
, *Request
)) {
2407 DefaultServeMux
.HandleFunc(pattern
, handler
)
2410 // Serve accepts incoming HTTP connections on the listener l,
2411 // creating a new service goroutine for each. The service goroutines
2412 // read requests and then call handler to reply to them.
2414 // The handler is typically nil, in which case the DefaultServeMux is used.
2416 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
2417 // connections and they were configured with "h2" in the TLS
2418 // Config.NextProtos.
2420 // Serve always returns a non-nil error.
2421 func Serve(l net
.Listener
, handler Handler
) error
{
2422 srv
:= &Server
{Handler
: handler
}
2426 // ServeTLS accepts incoming HTTPS connections on the listener l,
2427 // creating a new service goroutine for each. The service goroutines
2428 // read requests and then call handler to reply to them.
2430 // The handler is typically nil, in which case the DefaultServeMux is used.
2432 // Additionally, files containing a certificate and matching private key
2433 // for the server must be provided. If the certificate is signed by a
2434 // certificate authority, the certFile should be the concatenation
2435 // of the server's certificate, any intermediates, and the CA's certificate.
2437 // ServeTLS always returns a non-nil error.
2438 func ServeTLS(l net
.Listener
, handler Handler
, certFile
, keyFile
string) error
{
2439 srv
:= &Server
{Handler
: handler
}
2440 return srv
.ServeTLS(l
, certFile
, keyFile
)
2443 // A Server defines parameters for running an HTTP server.
2444 // The zero value for Server is a valid configuration.
2445 type Server
struct {
2446 Addr
string // TCP address to listen on, ":http" if empty
2447 Handler Handler
// handler to invoke, http.DefaultServeMux if nil
2449 // TLSConfig optionally provides a TLS configuration for use
2450 // by ServeTLS and ListenAndServeTLS. Note that this value is
2451 // cloned by ServeTLS and ListenAndServeTLS, so it's not
2452 // possible to modify the configuration with methods like
2453 // tls.Config.SetSessionTicketKeys. To use
2454 // SetSessionTicketKeys, use Server.Serve with a TLS Listener
2456 TLSConfig
*tls
.Config
2458 // ReadTimeout is the maximum duration for reading the entire
2459 // request, including the body.
2461 // Because ReadTimeout does not let Handlers make per-request
2462 // decisions on each request body's acceptable deadline or
2463 // upload rate, most users will prefer to use
2464 // ReadHeaderTimeout. It is valid to use them both.
2465 ReadTimeout time
.Duration
2467 // ReadHeaderTimeout is the amount of time allowed to read
2468 // request headers. The connection's read deadline is reset
2469 // after reading the headers and the Handler can decide what
2470 // is considered too slow for the body.
2471 ReadHeaderTimeout time
.Duration
2473 // WriteTimeout is the maximum duration before timing out
2474 // writes of the response. It is reset whenever a new
2475 // request's header is read. Like ReadTimeout, it does not
2476 // let Handlers make decisions on a per-request basis.
2477 WriteTimeout time
.Duration
2479 // IdleTimeout is the maximum amount of time to wait for the
2480 // next request when keep-alives are enabled. If IdleTimeout
2481 // is zero, the value of ReadTimeout is used. If both are
2482 // zero, ReadHeaderTimeout is used.
2483 IdleTimeout time
.Duration
2485 // MaxHeaderBytes controls the maximum number of bytes the
2486 // server will read parsing the request header's keys and
2487 // values, including the request line. It does not limit the
2488 // size of the request body.
2489 // If zero, DefaultMaxHeaderBytes is used.
2492 // TLSNextProto optionally specifies a function to take over
2493 // ownership of the provided TLS connection when an NPN/ALPN
2494 // protocol upgrade has occurred. The map key is the protocol
2495 // name negotiated. The Handler argument should be used to
2496 // handle HTTP requests and will initialize the Request's TLS
2497 // and RemoteAddr if not already set. The connection is
2498 // automatically closed when the function returns.
2499 // If TLSNextProto is not nil, HTTP/2 support is not enabled
2501 TLSNextProto
map[string]func(*Server
, *tls
.Conn
, Handler
)
2503 // ConnState specifies an optional callback function that is
2504 // called when a client connection changes state. See the
2505 // ConnState type and associated constants for details.
2506 ConnState
func(net
.Conn
, ConnState
)
2508 // ErrorLog specifies an optional logger for errors accepting
2509 // connections, unexpected behavior from handlers, and
2510 // underlying FileSystem errors.
2511 // If nil, logging is done via the log package's standard logger.
2512 ErrorLog
*log
.Logger
2514 disableKeepAlives
int32 // accessed atomically.
2515 inShutdown
int32 // accessed atomically (non-zero means we're in Shutdown)
2516 nextProtoOnce sync
.Once
// guards setupHTTP2_* init
2517 nextProtoErr error
// result of http2.ConfigureServer if used
2520 listeners
map[*net
.Listener
]struct{}
2521 activeConn
map[*conn
]struct{}
2522 doneChan
chan struct{}
2526 func (s
*Server
) getDoneChan() <-chan struct{} {
2529 return s
.getDoneChanLocked()
2532 func (s
*Server
) getDoneChanLocked() chan struct{} {
2533 if s
.doneChan
== nil {
2534 s
.doneChan
= make(chan struct{})
2539 func (s
*Server
) closeDoneChanLocked() {
2540 ch
:= s
.getDoneChanLocked()
2543 // Already closed. Don't close again.
2545 // Safe to close here. We're the only closer, guarded
2551 // Close immediately closes all active net.Listeners and any
2552 // connections in state StateNew, StateActive, or StateIdle. For a
2553 // graceful shutdown, use Shutdown.
2555 // Close does not attempt to close (and does not even know about)
2556 // any hijacked connections, such as WebSockets.
2558 // Close returns any error returned from closing the Server's
2559 // underlying Listener(s).
2560 func (srv
*Server
) Close() error
{
2561 atomic
.StoreInt32(&srv
.inShutdown
, 1)
2563 defer srv
.mu
.Unlock()
2564 srv
.closeDoneChanLocked()
2565 err
:= srv
.closeListenersLocked()
2566 for c
:= range srv
.activeConn
{
2568 delete(srv
.activeConn
, c
)
2573 // shutdownPollInterval is how often we poll for quiescence
2574 // during Server.Shutdown. This is lower during tests, to
2576 // Ideally we could find a solution that doesn't involve polling,
2577 // but which also doesn't have a high runtime cost (and doesn't
2578 // involve any contentious mutexes), but that is left as an
2579 // exercise for the reader.
2580 var shutdownPollInterval
= 500 * time
.Millisecond
2582 // Shutdown gracefully shuts down the server without interrupting any
2583 // active connections. Shutdown works by first closing all open
2584 // listeners, then closing all idle connections, and then waiting
2585 // indefinitely for connections to return to idle and then shut down.
2586 // If the provided context expires before the shutdown is complete,
2587 // Shutdown returns the context's error, otherwise it returns any
2588 // error returned from closing the Server's underlying Listener(s).
2590 // When Shutdown is called, Serve, ListenAndServe, and
2591 // ListenAndServeTLS immediately return ErrServerClosed. Make sure the
2592 // program doesn't exit and waits instead for Shutdown to return.
2594 // Shutdown does not attempt to close nor wait for hijacked
2595 // connections such as WebSockets. The caller of Shutdown should
2596 // separately notify such long-lived connections of shutdown and wait
2597 // for them to close, if desired. See RegisterOnShutdown for a way to
2598 // register shutdown notification functions.
2600 // Once Shutdown has been called on a server, it may not be reused;
2601 // future calls to methods such as Serve will return ErrServerClosed.
2602 func (srv
*Server
) Shutdown(ctx context
.Context
) error
{
2603 atomic
.StoreInt32(&srv
.inShutdown
, 1)
2606 lnerr
:= srv
.closeListenersLocked()
2607 srv
.closeDoneChanLocked()
2608 for _
, f
:= range srv
.onShutdown
{
2613 ticker
:= time
.NewTicker(shutdownPollInterval
)
2616 if srv
.closeIdleConns() {
2627 // RegisterOnShutdown registers a function to call on Shutdown.
2628 // This can be used to gracefully shutdown connections that have
2629 // undergone NPN/ALPN protocol upgrade or that have been hijacked.
2630 // This function should start protocol-specific graceful shutdown,
2631 // but should not wait for shutdown to complete.
2632 func (srv
*Server
) RegisterOnShutdown(f
func()) {
2634 srv
.onShutdown
= append(srv
.onShutdown
, f
)
2638 // closeIdleConns closes all idle connections and reports whether the
2639 // server is quiescent.
2640 func (s
*Server
) closeIdleConns() bool {
2644 for c
:= range s
.activeConn
{
2645 st
, unixSec
:= c
.getState()
2646 // Issue 22682: treat StateNew connections as if
2647 // they're idle if we haven't read the first request's
2648 // header in over 5 seconds.
2649 if st
== StateNew
&& unixSec
< time
.Now().Unix()-5 {
2652 if st
!= StateIdle || unixSec
== 0 {
2653 // Assume unixSec == 0 means it's a very new
2654 // connection, without state set yet.
2659 delete(s
.activeConn
, c
)
2664 func (s
*Server
) closeListenersLocked() error
{
2666 for ln
:= range s
.listeners
{
2667 if cerr
:= (*ln
).Close(); cerr
!= nil && err
== nil {
2670 delete(s
.listeners
, ln
)
2675 // A ConnState represents the state of a client connection to a server.
2676 // It's used by the optional Server.ConnState hook.
2680 // StateNew represents a new connection that is expected to
2681 // send a request immediately. Connections begin at this
2682 // state and then transition to either StateActive or
2684 StateNew ConnState
= iota
2686 // StateActive represents a connection that has read 1 or more
2687 // bytes of a request. The Server.ConnState hook for
2688 // StateActive fires before the request has entered a handler
2689 // and doesn't fire again until the request has been
2690 // handled. After the request is handled, the state
2691 // transitions to StateClosed, StateHijacked, or StateIdle.
2692 // For HTTP/2, StateActive fires on the transition from zero
2693 // to one active request, and only transitions away once all
2694 // active requests are complete. That means that ConnState
2695 // cannot be used to do per-request work; ConnState only notes
2696 // the overall state of the connection.
2699 // StateIdle represents a connection that has finished
2700 // handling a request and is in the keep-alive state, waiting
2701 // for a new request. Connections transition from StateIdle
2702 // to either StateActive or StateClosed.
2705 // StateHijacked represents a hijacked connection.
2706 // This is a terminal state. It does not transition to StateClosed.
2709 // StateClosed represents a closed connection.
2710 // This is a terminal state. Hijacked connections do not
2711 // transition to StateClosed.
2715 var stateName
= map[ConnState
]string{
2717 StateActive
: "active",
2719 StateHijacked
: "hijacked",
2720 StateClosed
: "closed",
2723 func (c ConnState
) String() string {
2727 // serverHandler delegates to either the server's Handler or
2728 // DefaultServeMux and also handles "OPTIONS *" requests.
2729 type serverHandler
struct {
2733 func (sh serverHandler
) ServeHTTP(rw ResponseWriter
, req
*Request
) {
2734 handler
:= sh
.srv
.Handler
2736 handler
= DefaultServeMux
2738 if req
.RequestURI
== "*" && req
.Method
== "OPTIONS" {
2739 handler
= globalOptionsHandler
{}
2741 handler
.ServeHTTP(rw
, req
)
2744 // ListenAndServe listens on the TCP network address srv.Addr and then
2745 // calls Serve to handle requests on incoming connections.
2746 // Accepted connections are configured to enable TCP keep-alives.
2748 // If srv.Addr is blank, ":http" is used.
2750 // ListenAndServe always returns a non-nil error. After Shutdown or Close,
2751 // the returned error is ErrServerClosed.
2752 func (srv
*Server
) ListenAndServe() error
{
2753 if srv
.shuttingDown() {
2754 return ErrServerClosed
2760 ln
, err
:= net
.Listen("tcp", addr
)
2764 return srv
.Serve(tcpKeepAliveListener
{ln
.(*net
.TCPListener
)})
2767 var testHookServerServe
func(*Server
, net
.Listener
) // used if non-nil
2769 // shouldDoServeHTTP2 reports whether Server.Serve should configure
2770 // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
2771 func (srv
*Server
) shouldConfigureHTTP2ForServe() bool {
2772 if srv
.TLSConfig
== nil {
2773 // Compatibility with Go 1.6:
2774 // If there's no TLSConfig, it's possible that the user just
2775 // didn't set it on the http.Server, but did pass it to
2776 // tls.NewListener and passed that listener to Serve.
2777 // So we should configure HTTP/2 (to set up srv.TLSNextProto)
2778 // in case the listener returns an "h2" *tls.Conn.
2781 // The user specified a TLSConfig on their http.Server.
2782 // In this, case, only configure HTTP/2 if their tls.Config
2783 // explicitly mentions "h2". Otherwise http2.ConfigureServer
2784 // would modify the tls.Config to add it, but they probably already
2785 // passed this tls.Config to tls.NewListener. And if they did,
2786 // it's too late anyway to fix it. It would only be potentially racy.
2788 return strSliceContains(srv
.TLSConfig
.NextProtos
, http2NextProtoTLS
)
2791 // ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
2792 // and ListenAndServeTLS methods after a call to Shutdown or Close.
2793 var ErrServerClosed
= errors
.New("http: Server closed")
2795 // Serve accepts incoming connections on the Listener l, creating a
2796 // new service goroutine for each. The service goroutines read requests and
2797 // then call srv.Handler to reply to them.
2799 // HTTP/2 support is only enabled if the Listener returns *tls.Conn
2800 // connections and they were configured with "h2" in the TLS
2801 // Config.NextProtos.
2803 // Serve always returns a non-nil error and closes l.
2804 // After Shutdown or Close, the returned error is ErrServerClosed.
2805 func (srv
*Server
) Serve(l net
.Listener
) error
{
2806 if fn
:= testHookServerServe
; fn
!= nil {
2807 fn(srv
, l
) // call hook with unwrapped listener
2810 l
= &onceCloseListener
{Listener
: l
}
2813 if err
:= srv
.setupHTTP2_Serve(); err
!= nil {
2817 if !srv
.trackListener(&l
, true) {
2818 return ErrServerClosed
2820 defer srv
.trackListener(&l
, false)
2822 var tempDelay time
.Duration
// how long to sleep on accept failure
2823 baseCtx
:= context
.Background() // base is always background, per Issue 16220
2824 ctx
:= context
.WithValue(baseCtx
, ServerContextKey
, srv
)
2829 case <-srv
.getDoneChan():
2830 return ErrServerClosed
2833 if ne
, ok
:= e
.(net
.Error
); ok
&& ne
.Temporary() {
2835 tempDelay
= 5 * time
.Millisecond
2839 if max
:= 1 * time
.Second
; tempDelay
> max
{
2842 srv
.logf("http: Accept error: %v; retrying in %v", e
, tempDelay
)
2843 time
.Sleep(tempDelay
)
2849 c
:= srv
.newConn(rw
)
2850 c
.setState(c
.rwc
, StateNew
) // before Serve can return
2855 // ServeTLS accepts incoming connections on the Listener l, creating a
2856 // new service goroutine for each. The service goroutines perform TLS
2857 // setup and then read requests, calling srv.Handler to reply to them.
2859 // Files containing a certificate and matching private key for the
2860 // server must be provided if neither the Server's
2861 // TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
2862 // If the certificate is signed by a certificate authority, the
2863 // certFile should be the concatenation of the server's certificate,
2864 // any intermediates, and the CA's certificate.
2866 // ServeTLS always returns a non-nil error. After Shutdown or Close, the
2867 // returned error is ErrServerClosed.
2868 func (srv
*Server
) ServeTLS(l net
.Listener
, certFile
, keyFile
string) error
{
2869 // Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
2870 // before we clone it and create the TLS Listener.
2871 if err
:= srv
.setupHTTP2_ServeTLS(); err
!= nil {
2875 config
:= cloneTLSConfig(srv
.TLSConfig
)
2876 if !strSliceContains(config
.NextProtos
, "http/1.1") {
2877 config
.NextProtos
= append(config
.NextProtos
, "http/1.1")
2880 configHasCert
:= len(config
.Certificates
) > 0 || config
.GetCertificate
!= nil
2881 if !configHasCert || certFile
!= "" || keyFile
!= "" {
2883 config
.Certificates
= make([]tls
.Certificate
, 1)
2884 config
.Certificates
[0], err
= tls
.LoadX509KeyPair(certFile
, keyFile
)
2890 tlsListener
:= tls
.NewListener(l
, config
)
2891 return srv
.Serve(tlsListener
)
2894 // trackListener adds or removes a net.Listener to the set of tracked
2897 // We store a pointer to interface in the map set, in case the
2898 // net.Listener is not comparable. This is safe because we only call
2899 // trackListener via Serve and can track+defer untrack the same
2900 // pointer to local variable there. We never need to compare a
2901 // Listener from another caller.
2903 // It reports whether the server is still up (not Shutdown or Closed).
2904 func (s
*Server
) trackListener(ln
*net
.Listener
, add
bool) bool {
2907 if s
.listeners
== nil {
2908 s
.listeners
= make(map[*net
.Listener
]struct{})
2911 if s
.shuttingDown() {
2914 s
.listeners
[ln
] = struct{}{}
2916 delete(s
.listeners
, ln
)
2921 func (s
*Server
) trackConn(c
*conn
, add
bool) {
2924 if s
.activeConn
== nil {
2925 s
.activeConn
= make(map[*conn
]struct{})
2928 s
.activeConn
[c
] = struct{}{}
2930 delete(s
.activeConn
, c
)
2934 func (s
*Server
) idleTimeout() time
.Duration
{
2935 if s
.IdleTimeout
!= 0 {
2936 return s
.IdleTimeout
2938 return s
.ReadTimeout
2941 func (s
*Server
) readHeaderTimeout() time
.Duration
{
2942 if s
.ReadHeaderTimeout
!= 0 {
2943 return s
.ReadHeaderTimeout
2945 return s
.ReadTimeout
2948 func (s
*Server
) doKeepAlives() bool {
2949 return atomic
.LoadInt32(&s
.disableKeepAlives
) == 0 && !s
.shuttingDown()
2952 func (s
*Server
) shuttingDown() bool {
2953 // TODO: replace inShutdown with the existing atomicBool type;
2954 // see https://github.com/golang/go/issues/20239#issuecomment-381434582
2955 return atomic
.LoadInt32(&s
.inShutdown
) != 0
2958 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
2959 // By default, keep-alives are always enabled. Only very
2960 // resource-constrained environments or servers in the process of
2961 // shutting down should disable them.
2962 func (srv
*Server
) SetKeepAlivesEnabled(v
bool) {
2964 atomic
.StoreInt32(&srv
.disableKeepAlives
, 0)
2967 atomic
.StoreInt32(&srv
.disableKeepAlives
, 1)
2969 // Close idle HTTP/1 conns:
2970 srv
.closeIdleConns()
2972 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
2975 func (s
*Server
) logf(format
string, args
...interface{}) {
2976 if s
.ErrorLog
!= nil {
2977 s
.ErrorLog
.Printf(format
, args
...)
2979 log
.Printf(format
, args
...)
2983 // logf prints to the ErrorLog of the *Server associated with request r
2984 // via ServerContextKey. If there's no associated server, or if ErrorLog
2985 // is nil, logging is done via the log package's standard logger.
2986 func logf(r
*Request
, format
string, args
...interface{}) {
2987 s
, _
:= r
.Context().Value(ServerContextKey
).(*Server
)
2988 if s
!= nil && s
.ErrorLog
!= nil {
2989 s
.ErrorLog
.Printf(format
, args
...)
2991 log
.Printf(format
, args
...)
2995 // ListenAndServe listens on the TCP network address addr and then calls
2996 // Serve with handler to handle requests on incoming connections.
2997 // Accepted connections are configured to enable TCP keep-alives.
2999 // The handler is typically nil, in which case the DefaultServeMux is used.
3001 // ListenAndServe always returns a non-nil error.
3002 func ListenAndServe(addr
string, handler Handler
) error
{
3003 server
:= &Server
{Addr
: addr
, Handler
: handler
}
3004 return server
.ListenAndServe()
3007 // ListenAndServeTLS acts identically to ListenAndServe, except that it
3008 // expects HTTPS connections. Additionally, files containing a certificate and
3009 // matching private key for the server must be provided. If the certificate
3010 // is signed by a certificate authority, the certFile should be the concatenation
3011 // of the server's certificate, any intermediates, and the CA's certificate.
3012 func ListenAndServeTLS(addr
, certFile
, keyFile
string, handler Handler
) error
{
3013 server
:= &Server
{Addr
: addr
, Handler
: handler
}
3014 return server
.ListenAndServeTLS(certFile
, keyFile
)
3017 // ListenAndServeTLS listens on the TCP network address srv.Addr and
3018 // then calls ServeTLS to handle requests on incoming TLS connections.
3019 // Accepted connections are configured to enable TCP keep-alives.
3021 // Filenames containing a certificate and matching private key for the
3022 // server must be provided if neither the Server's TLSConfig.Certificates
3023 // nor TLSConfig.GetCertificate are populated. If the certificate is
3024 // signed by a certificate authority, the certFile should be the
3025 // concatenation of the server's certificate, any intermediates, and
3026 // the CA's certificate.
3028 // If srv.Addr is blank, ":https" is used.
3030 // ListenAndServeTLS always returns a non-nil error. After Shutdown or
3031 // Close, the returned error is ErrServerClosed.
3032 func (srv
*Server
) ListenAndServeTLS(certFile
, keyFile
string) error
{
3033 if srv
.shuttingDown() {
3034 return ErrServerClosed
3041 ln
, err
:= net
.Listen("tcp", addr
)
3048 return srv
.ServeTLS(tcpKeepAliveListener
{ln
.(*net
.TCPListener
)}, certFile
, keyFile
)
3051 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
3052 // srv and returns whether there was an error setting it up. If it is
3053 // not configured for policy reasons, nil is returned.
3054 func (srv
*Server
) setupHTTP2_ServeTLS() error
{
3055 srv
.nextProtoOnce
.Do(srv
.onceSetNextProtoDefaults
)
3056 return srv
.nextProtoErr
3059 // setupHTTP2_Serve is called from (*Server).Serve and conditionally
3060 // configures HTTP/2 on srv using a more conservative policy than
3061 // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
3062 // and may be called concurrently. See shouldConfigureHTTP2ForServe.
3064 // The tests named TestTransportAutomaticHTTP2* and
3065 // TestConcurrentServerServe in server_test.go demonstrate some
3066 // of the supported use cases and motivations.
3067 func (srv
*Server
) setupHTTP2_Serve() error
{
3068 srv
.nextProtoOnce
.Do(srv
.onceSetNextProtoDefaults_Serve
)
3069 return srv
.nextProtoErr
3072 func (srv
*Server
) onceSetNextProtoDefaults_Serve() {
3073 if srv
.shouldConfigureHTTP2ForServe() {
3074 srv
.onceSetNextProtoDefaults()
3078 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
3079 // configured otherwise. (by setting srv.TLSNextProto non-nil)
3080 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
3081 func (srv
*Server
) onceSetNextProtoDefaults() {
3082 if strings
.Contains(os
.Getenv("GODEBUG"), "http2server=0") {
3085 // Enable HTTP/2 by default if the user hasn't otherwise
3086 // configured their TLSNextProto map.
3087 if srv
.TLSNextProto
== nil {
3088 conf
:= &http2Server
{
3089 NewWriteScheduler
: func() http2WriteScheduler
{ return http2NewPriorityWriteScheduler(nil) },
3091 srv
.nextProtoErr
= http2ConfigureServer(srv
, conf
)
3095 // TimeoutHandler returns a Handler that runs h with the given time limit.
3097 // The new Handler calls h.ServeHTTP to handle each request, but if a
3098 // call runs for longer than its time limit, the handler responds with
3099 // a 503 Service Unavailable error and the given message in its body.
3100 // (If msg is empty, a suitable default message will be sent.)
3101 // After such a timeout, writes by h to its ResponseWriter will return
3102 // ErrHandlerTimeout.
3104 // TimeoutHandler buffers all Handler writes to memory and does not
3105 // support the Hijacker or Flusher interfaces.
3106 func TimeoutHandler(h Handler
, dt time
.Duration
, msg
string) Handler
{
3107 return &timeoutHandler
{
3114 // ErrHandlerTimeout is returned on ResponseWriter Write calls
3115 // in handlers which have timed out.
3116 var ErrHandlerTimeout
= errors
.New("http: Handler timeout")
3118 type timeoutHandler
struct {
3123 // When set, no context will be created and this context will
3125 testContext context
.Context
3128 func (h
*timeoutHandler
) errorBody() string {
3132 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
3135 func (h
*timeoutHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
3136 ctx
:= h
.testContext
3138 var cancelCtx context
.CancelFunc
3139 ctx
, cancelCtx
= context
.WithTimeout(r
.Context(), h
.dt
)
3142 r
= r
.WithContext(ctx
)
3143 done
:= make(chan struct{})
3144 tw
:= &timeoutWriter
{
3148 panicChan
:= make(chan interface{}, 1)
3151 if p
:= recover(); p
!= nil {
3155 h
.handler
.ServeHTTP(tw
, r
)
3159 case p
:= <-panicChan
:
3163 defer tw
.mu
.Unlock()
3165 for k
, vv
:= range tw
.h
{
3168 if !tw
.wroteHeader
{
3171 w
.WriteHeader(tw
.code
)
3172 w
.Write(tw
.wbuf
.Bytes())
3175 defer tw
.mu
.Unlock()
3176 w
.WriteHeader(StatusServiceUnavailable
)
3177 io
.WriteString(w
, h
.errorBody())
3183 type timeoutWriter
struct {
3194 func (tw
*timeoutWriter
) Header() Header
{ return tw
.h
}
3196 func (tw
*timeoutWriter
) Write(p
[]byte) (int, error
) {
3198 defer tw
.mu
.Unlock()
3200 return 0, ErrHandlerTimeout
3202 if !tw
.wroteHeader
{
3203 tw
.writeHeader(StatusOK
)
3205 return tw
.wbuf
.Write(p
)
3208 func (tw
*timeoutWriter
) WriteHeader(code
int) {
3209 checkWriteHeaderCode(code
)
3211 defer tw
.mu
.Unlock()
3212 if tw
.timedOut || tw
.wroteHeader
{
3215 tw
.writeHeader(code
)
3218 func (tw
*timeoutWriter
) writeHeader(code
int) {
3219 tw
.wroteHeader
= true
3223 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
3224 // connections. It's used by ListenAndServe and ListenAndServeTLS so
3225 // dead TCP connections (e.g. closing laptop mid-download) eventually
3227 type tcpKeepAliveListener
struct {
3231 func (ln tcpKeepAliveListener
) Accept() (net
.Conn
, error
) {
3232 tc
, err
:= ln
.AcceptTCP()
3236 tc
.SetKeepAlive(true)
3237 tc
.SetKeepAlivePeriod(3 * time
.Minute
)
3241 // onceCloseListener wraps a net.Listener, protecting it from
3242 // multiple Close calls.
3243 type onceCloseListener
struct {
3249 func (oc
*onceCloseListener
) Close() error
{
3250 oc
.once
.Do(oc
.close)
3254 func (oc
*onceCloseListener
) close() { oc
.closeErr
= oc
.Listener
.Close() }
3256 // globalOptionsHandler responds to "OPTIONS *" requests.
3257 type globalOptionsHandler
struct{}
3259 func (globalOptionsHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
3260 w
.Header().Set("Content-Length", "0")
3261 if r
.ContentLength
!= 0 {
3262 // Read up to 4KB of OPTIONS body (as mentioned in the
3263 // spec as being reserved for future use), but anything
3264 // over that is considered a waste of server resources
3265 // (or an attack) and we abort and close the connection,
3266 // courtesy of MaxBytesReader's EOF behavior.
3267 mb
:= MaxBytesReader(w
, r
.Body
, 4<<10)
3268 io
.Copy(ioutil
.Discard
, mb
)
3272 // initNPNRequest is an HTTP handler that initializes certain
3273 // uninitialized fields in its *Request. Such partially-initialized
3274 // Requests come from NPN protocol handlers.
3275 type initNPNRequest
struct {
3280 func (h initNPNRequest
) ServeHTTP(rw ResponseWriter
, req
*Request
) {
3282 req
.TLS
= &tls
.ConnectionState
{}
3283 *req
.TLS
= h
.c
.ConnectionState()
3285 if req
.Body
== nil {
3288 if req
.RemoteAddr
== "" {
3289 req
.RemoteAddr
= h
.c
.RemoteAddr().String()
3291 h
.h
.ServeHTTP(rw
, req
)
3294 // loggingConn is used for debugging.
3295 type loggingConn
struct {
3301 uniqNameMu sync
.Mutex
3302 uniqNameNext
= make(map[string]int)
3305 func newLoggingConn(baseName
string, c net
.Conn
) net
.Conn
{
3307 defer uniqNameMu
.Unlock()
3308 uniqNameNext
[baseName
]++
3309 return &loggingConn
{
3310 name
: fmt
.Sprintf("%s-%d", baseName
, uniqNameNext
[baseName
]),
3315 func (c
*loggingConn
) Write(p
[]byte) (n
int, err error
) {
3316 log
.Printf("%s.Write(%d) = ....", c
.name
, len(p
))
3317 n
, err
= c
.Conn
.Write(p
)
3318 log
.Printf("%s.Write(%d) = %d, %v", c
.name
, len(p
), n
, err
)
3322 func (c
*loggingConn
) Read(p
[]byte) (n
int, err error
) {
3323 log
.Printf("%s.Read(%d) = ....", c
.name
, len(p
))
3324 n
, err
= c
.Conn
.Read(p
)
3325 log
.Printf("%s.Read(%d) = %d, %v", c
.name
, len(p
), n
, err
)
3329 func (c
*loggingConn
) Close() (err error
) {
3330 log
.Printf("%s.Close() = ...", c
.name
)
3331 err
= c
.Conn
.Close()
3332 log
.Printf("%s.Close() = %v", c
.name
, err
)
3336 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
3337 // It only contains one field (and a pointer field at that), so it
3338 // fits in an interface value without an extra allocation.
3339 type checkConnErrorWriter
struct {
3343 func (w checkConnErrorWriter
) Write(p
[]byte) (n
int, err error
) {
3344 n
, err
= w
.c
.rwc
.Write(p
)
3345 if err
!= nil && w
.c
.werr
== nil {
3352 func numLeadingCRorLF(v
[]byte) (n
int) {
3353 for _
, b
:= range v
{
3354 if b
== '\r' || b
== '\n' {
3364 func strSliceContains(ss
[]string, s
string) bool {
3365 for _
, v
:= range ss
{