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 2616.
29 // Errors introduced by the HTTP server.
31 ErrWriteAfterFlush
= errors
.New("Conn.Write called after Flush")
32 ErrBodyNotAllowed
= errors
.New("http: request method or response status code does not allow body")
33 ErrHijacked
= errors
.New("Conn has been hijacked")
34 ErrContentLength
= errors
.New("Conn.Write wrote more than the declared Content-Length")
37 // Objects implementing the Handler interface can be
38 // registered to serve a particular path or subtree
39 // in the HTTP server.
41 // ServeHTTP should write reply headers and data to the ResponseWriter
42 // and then return. Returning signals that the request is finished
43 // and that the HTTP server can move on to the next request on
45 type Handler
interface {
46 ServeHTTP(ResponseWriter
, *Request
)
49 // A ResponseWriter interface is used by an HTTP handler to
50 // construct an HTTP response.
51 type ResponseWriter
interface {
52 // Header returns the header map that will be sent by WriteHeader.
53 // Changing the header after a call to WriteHeader (or Write) has
57 // Write writes the data to the connection as part of an HTTP reply.
58 // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
59 // before writing the data. If the Header does not contain a
60 // Content-Type line, Write adds a Content-Type set to the result of passing
61 // the initial 512 bytes of written data to DetectContentType.
62 Write([]byte) (int, error
)
64 // WriteHeader sends an HTTP response header with status code.
65 // If WriteHeader is not called explicitly, the first call to Write
66 // will trigger an implicit WriteHeader(http.StatusOK).
67 // Thus explicit calls to WriteHeader are mainly used to
72 // The Flusher interface is implemented by ResponseWriters that allow
73 // an HTTP handler to flush buffered data to the client.
75 // Note that even for ResponseWriters that support Flush,
76 // if the client is connected through an HTTP proxy,
77 // the buffered data may not reach the client until the response
79 type Flusher
interface {
80 // Flush sends any buffered data to the client.
84 // The Hijacker interface is implemented by ResponseWriters that allow
85 // an HTTP handler to take over the connection.
86 type Hijacker
interface {
87 // Hijack lets the caller take over the connection.
88 // After a call to Hijack(), the HTTP server library
89 // will not do anything else with the connection.
90 // It becomes the caller's responsibility to manage
91 // and close the connection.
92 Hijack() (net
.Conn
, *bufio
.ReadWriter
, error
)
95 // The CloseNotifier interface is implemented by ResponseWriters which
96 // allow detecting when the underlying connection has gone away.
98 // This mechanism can be used to cancel long operations on the server
99 // if the client has disconnected before the response is ready.
100 type CloseNotifier
interface {
101 // CloseNotify returns a channel that receives a single value
102 // when the client connection has gone away.
103 CloseNotify() <-chan bool
106 // A conn represents the server side of an HTTP connection.
108 remoteAddr
string // network address of remote side
109 server
*Server
// the Server on which the connection arrived
110 rwc net
.Conn
// i/o connection
111 sr liveSwitchReader
// where the LimitReader reads from; usually the rwc
112 lr
*io
.LimitedReader
// io.LimitReader(sr)
113 buf
*bufio
.ReadWriter
// buffered(lr,rwc), reading from bufio->limitReader->sr->rwc
114 tlsState
*tls
.ConnectionState
// or nil when not using TLS
116 mu sync
.Mutex
// guards the following
117 clientGone
bool // if client has disconnected mid-request
118 closeNotifyc
chan bool // made lazily
119 hijackedv
bool // connection has been hijacked by handler
122 func (c
*conn
) hijacked() bool {
128 func (c
*conn
) hijack() (rwc net
.Conn
, buf
*bufio
.ReadWriter
, err error
) {
132 return nil, nil, ErrHijacked
134 if c
.closeNotifyc
!= nil {
135 return nil, nil, errors
.New("http: Hijack is incompatible with use of CloseNotifier")
142 c
.setState(rwc
, StateHijacked
)
146 func (c
*conn
) closeNotify() <-chan bool {
149 if c
.closeNotifyc
== nil {
150 c
.closeNotifyc
= make(chan bool, 1)
152 // to obey the function signature, even though
153 // it'll never receive a value.
154 return c
.closeNotifyc
163 _
, err
:= io
.Copy(pw
, readSource
)
167 pw
.CloseWithError(err
)
171 return c
.closeNotifyc
174 func (c
*conn
) noteClientGone() {
177 if c
.closeNotifyc
!= nil && !c
.clientGone
{
178 c
.closeNotifyc
<- true
183 // A switchReader can have its Reader changed at runtime.
184 // It's not safe for concurrent Reads and switches.
185 type switchReader
struct {
189 // A switchWriter can have its Writer changed at runtime.
190 // It's not safe for concurrent Writes and switches.
191 type switchWriter
struct {
195 // A liveSwitchReader is a switchReader that's safe for concurrent
196 // reads and switches, if its mutex is held.
197 type liveSwitchReader
struct {
202 func (sr
*liveSwitchReader
) Read(p
[]byte) (n
int, err error
) {
209 // This should be >= 512 bytes for DetectContentType,
210 // but otherwise it's somewhat arbitrary.
211 const bufferBeforeChunkingSize
= 2048
213 // chunkWriter writes to a response's conn buffer, and is the writer
214 // wrapped by the response.bufw buffered writer.
216 // chunkWriter also is responsible for finalizing the Header, including
217 // conditionally setting the Content-Type and setting a Content-Length
218 // in cases where the handler's final output is smaller than the buffer
219 // size. It also conditionally adds chunk headers, when in chunking mode.
221 // See the comment above (*response).Write for the entire write flow.
222 type chunkWriter
struct {
225 // header is either nil or a deep clone of res.handlerHeader
226 // at the time of res.WriteHeader, if res.WriteHeader is
227 // called and extra buffering is being done to calculate
228 // Content-Type and/or Content-Length.
231 // wroteHeader tells whether the header's been written to "the
232 // wire" (or rather: w.conn.buf). this is unlike
233 // (*response).wroteHeader, which tells only whether it was
234 // logically written.
237 // set by the writeHeader method:
238 chunking
bool // using chunked transfer encoding for reply body
242 crlf
= []byte("\r\n")
243 colonSpace
= []byte(": ")
246 func (cw
*chunkWriter
) Write(p
[]byte) (n
int, err error
) {
250 if cw
.res
.req
.Method
== "HEAD" {
255 _
, err
= fmt
.Fprintf(cw
.res
.conn
.buf
, "%x\r\n", len(p
))
257 cw
.res
.conn
.rwc
.Close()
261 n
, err
= cw
.res
.conn
.buf
.Write(p
)
262 if cw
.chunking
&& err
== nil {
263 _
, err
= cw
.res
.conn
.buf
.Write(crlf
)
266 cw
.res
.conn
.rwc
.Close()
271 func (cw
*chunkWriter
) flush() {
275 cw
.res
.conn
.buf
.Flush()
278 func (cw
*chunkWriter
) close() {
283 // zero EOF chunk, trailer key/value pairs (currently
284 // unsupported in Go's server), followed by a blank
286 cw
.res
.conn
.buf
.WriteString("0\r\n\r\n")
290 // A response represents the server side of an HTTP response.
291 type response
struct {
293 req
*Request
// request for this response
294 wroteHeader
bool // reply header has been (logically) written
295 wroteContinue
bool // 100 Continue response was written
297 w
*bufio
.Writer
// buffers output in chunks to chunkWriter
299 sw
*switchWriter
// of the bufio.Writer, for return to putBufioWriter
301 // handlerHeader is the Header that Handlers get access to,
302 // which may be retained and mutated even after WriteHeader.
303 // handlerHeader is copied into cw.header at WriteHeader
304 // time, and privately mutated thereafter.
306 calledHeader
bool // handler accessed handlerHeader via Header
308 written
int64 // number of bytes written in body
309 contentLength
int64 // explicitly-declared Content-Length; or -1
310 status
int // status code passed to WriteHeader
312 // close connection after this reply. set on request and
313 // updated after response from handler if there's a
314 // "Connection: keep-alive" response header and a
318 // requestBodyLimitHit is set by requestTooLarge when
319 // maxBytesReader hits its max size. It is checked in
320 // WriteHeader, to make sure we don't consume the
321 // remaining request body to try to advance to the next HTTP
322 // request. Instead, when this is set, we stop reading
323 // subsequent requests on this connection and stop reading
325 requestBodyLimitHit
bool
327 handlerDone
bool // set true when the handler exits
329 // Buffers for Date and Content-Length
330 dateBuf
[len(TimeFormat
)]byte
334 // requestTooLarge is called by maxBytesReader when too much input has
335 // been read from the client.
336 func (w
*response
) requestTooLarge() {
337 w
.closeAfterReply
= true
338 w
.requestBodyLimitHit
= true
340 w
.Header().Set("Connection", "close")
344 // needsSniff reports whether a Content-Type still needs to be sniffed.
345 func (w
*response
) needsSniff() bool {
346 _
, haveType
:= w
.handlerHeader
["Content-Type"]
347 return !w
.cw
.wroteHeader
&& !haveType
&& w
.written
< sniffLen
350 // writerOnly hides an io.Writer value's optional ReadFrom method
352 type writerOnly
struct {
356 func srcIsRegularFile(src io
.Reader
) (isRegular
bool, err error
) {
357 switch v
:= src
.(type) {
363 return fi
.Mode().IsRegular(), nil
364 case *io
.LimitedReader
:
365 return srcIsRegularFile(v
.R
)
371 // ReadFrom is here to optimize copying from an *os.File regular file
372 // to a *net.TCPConn with sendfile.
373 func (w
*response
) ReadFrom(src io
.Reader
) (n
int64, err error
) {
374 // Our underlying w.conn.rwc is usually a *TCPConn (with its
375 // own ReadFrom method). If not, or if our src isn't a regular
376 // file, just fall back to the normal copy method.
377 rf
, ok
:= w
.conn
.rwc
.(io
.ReaderFrom
)
378 regFile
, err
:= srcIsRegularFile(src
)
383 return io
.Copy(writerOnly
{w
}, src
)
389 w
.WriteHeader(StatusOK
)
393 n0
, err
:= io
.Copy(writerOnly
{w
}, io
.LimitReader(src
, sniffLen
))
400 w
.w
.Flush() // get rid of any previous writes
401 w
.cw
.flush() // make sure Header is written; flush data to rwc
403 // Now that cw has been flushed, its chunking field is guaranteed initialized.
404 if !w
.cw
.chunking
&& w
.bodyAllowed() {
405 n0
, err
:= rf
.ReadFrom(src
)
411 n0
, err
:= io
.Copy(writerOnly
{w
}, src
)
416 // noLimit is an effective infinite upper bound for io.LimitedReader
417 const noLimit
int64 = (1 << 63) - 1
419 // debugServerConnections controls whether all server connections are wrapped
420 // with a verbose logging wrapper.
421 const debugServerConnections
= false
423 // Create new connection from rwc.
424 func (srv
*Server
) newConn(rwc net
.Conn
) (c
*conn
, err error
) {
426 c
.remoteAddr
= rwc
.RemoteAddr().String()
429 if debugServerConnections
{
430 c
.rwc
= newLoggingConn("server", c
.rwc
)
432 c
.sr
= liveSwitchReader
{r
: c
.rwc
}
433 c
.lr
= io
.LimitReader(&c
.sr
, noLimit
).(*io
.LimitedReader
)
434 br
:= newBufioReader(c
.lr
)
435 bw
:= newBufioWriterSize(c
.rwc
, 4<<10)
436 c
.buf
= bufio
.NewReadWriter(br
, bw
)
441 bufioReaderPool sync
.Pool
442 bufioWriter2kPool sync
.Pool
443 bufioWriter4kPool sync
.Pool
446 func bufioWriterPool(size
int) *sync
.Pool
{
449 return &bufioWriter2kPool
451 return &bufioWriter4kPool
456 func newBufioReader(r io
.Reader
) *bufio
.Reader
{
457 if v
:= bufioReaderPool
.Get(); v
!= nil {
458 br
:= v
.(*bufio
.Reader
)
462 return bufio
.NewReader(r
)
465 func putBufioReader(br
*bufio
.Reader
) {
467 bufioReaderPool
.Put(br
)
470 func newBufioWriterSize(w io
.Writer
, size
int) *bufio
.Writer
{
471 pool
:= bufioWriterPool(size
)
473 if v
:= pool
.Get(); v
!= nil {
474 bw
:= v
.(*bufio
.Writer
)
479 return bufio
.NewWriterSize(w
, size
)
482 func putBufioWriter(bw
*bufio
.Writer
) {
484 if pool
:= bufioWriterPool(bw
.Available()); pool
!= nil {
489 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
490 // in an HTTP request.
491 // This can be overridden by setting Server.MaxHeaderBytes.
492 const DefaultMaxHeaderBytes
= 1 << 20 // 1 MB
494 func (srv
*Server
) maxHeaderBytes() int {
495 if srv
.MaxHeaderBytes
> 0 {
496 return srv
.MaxHeaderBytes
498 return DefaultMaxHeaderBytes
501 func (srv
*Server
) initialLimitedReaderSize() int64 {
502 return int64(srv
.maxHeaderBytes()) + 4096 // bufio slop
505 // wrapper around io.ReaderCloser which on first read, sends an
506 // HTTP/1.1 100 Continue header
507 type expectContinueReader
struct {
509 readCloser io
.ReadCloser
513 func (ecr
*expectContinueReader
) Read(p
[]byte) (n
int, err error
) {
515 return 0, ErrBodyReadAfterClose
517 if !ecr
.resp
.wroteContinue
&& !ecr
.resp
.conn
.hijacked() {
518 ecr
.resp
.wroteContinue
= true
519 ecr
.resp
.conn
.buf
.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
520 ecr
.resp
.conn
.buf
.Flush()
522 return ecr
.readCloser
.Read(p
)
525 func (ecr
*expectContinueReader
) Close() error
{
527 return ecr
.readCloser
.Close()
530 // TimeFormat is the time format to use with
531 // time.Parse and time.Time.Format when parsing
532 // or generating times in HTTP headers.
533 // It is like time.RFC1123 but hard codes GMT as the time zone.
534 const TimeFormat
= "Mon, 02 Jan 2006 15:04:05 GMT"
536 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
537 func appendTime(b
[]byte, t time
.Time
) []byte {
538 const days
= "SunMonTueWedThuFriSat"
539 const months
= "JanFebMarAprMayJunJulAugSepOctNovDec"
542 yy
, mm
, dd
:= t
.Date()
543 hh
, mn
, ss
:= t
.Clock()
544 day
:= days
[3*t
.Weekday():]
545 mon
:= months
[3*(mm
-1):]
548 day
[0], day
[1], day
[2], ',', ' ',
549 byte('0'+dd
/10), byte('0'+dd%10
), ' ',
550 mon
[0], mon
[1], mon
[2], ' ',
551 byte('0'+yy
/1000), byte('0'+(yy
/100)%10
), byte('0'+(yy
/10)%10
), byte('0'+yy%10
), ' ',
552 byte('0'+hh
/10), byte('0'+hh%10
), ':',
553 byte('0'+mn
/10), byte('0'+mn%10
), ':',
554 byte('0'+ss
/10), byte('0'+ss%10
), ' ',
558 var errTooLarge
= errors
.New("http: request too large")
560 // Read next request from connection.
561 func (c
*conn
) readRequest() (w
*response
, err error
) {
563 return nil, ErrHijacked
566 if d
:= c
.server
.ReadTimeout
; d
!= 0 {
567 c
.rwc
.SetReadDeadline(time
.Now().Add(d
))
569 if d
:= c
.server
.WriteTimeout
; d
!= 0 {
571 c
.rwc
.SetWriteDeadline(time
.Now().Add(d
))
575 c
.lr
.N
= c
.server
.initialLimitedReaderSize()
577 if req
, err
= ReadRequest(c
.buf
.Reader
); err
!= nil {
579 return nil, errTooLarge
585 req
.RemoteAddr
= c
.remoteAddr
591 handlerHeader
: make(Header
),
595 w
.w
= newBufioWriterSize(&w
.cw
, bufferBeforeChunkingSize
)
599 func (w
*response
) Header() Header
{
600 if w
.cw
.header
== nil && w
.wroteHeader
&& !w
.cw
.wroteHeader
{
601 // Accessing the header between logically writing it
602 // and physically writing it means we need to allocate
603 // a clone to snapshot the logically written state.
604 w
.cw
.header
= w
.handlerHeader
.clone()
606 w
.calledHeader
= true
607 return w
.handlerHeader
610 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
611 // consumed by a handler that the server will read from the client
612 // in order to keep a connection alive. If there are more bytes than
613 // this then the server to be paranoid instead sends a "Connection:
616 // This number is approximately what a typical machine's TCP buffer
617 // size is anyway. (if we have the bytes on the machine, we might as
619 const maxPostHandlerReadBytes
= 256 << 10
621 func (w
*response
) WriteHeader(code
int) {
622 if w
.conn
.hijacked() {
623 w
.conn
.server
.logf("http: response.WriteHeader on hijacked connection")
627 w
.conn
.server
.logf("http: multiple response.WriteHeader calls")
633 if w
.calledHeader
&& w
.cw
.header
== nil {
634 w
.cw
.header
= w
.handlerHeader
.clone()
637 if cl
:= w
.handlerHeader
.get("Content-Length"); cl
!= "" {
638 v
, err
:= strconv
.ParseInt(cl
, 10, 64)
639 if err
== nil && v
>= 0 {
642 w
.conn
.server
.logf("http: invalid Content-Length of %q", cl
)
643 w
.handlerHeader
.Del("Content-Length")
648 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
649 // This type is used to avoid extra allocations from cloning and/or populating
650 // the response Header map and all its 1-element slices.
651 type extraHeader
struct {
654 transferEncoding
string
655 date
[]byte // written if not nil
656 contentLength
[]byte // written if not nil
659 // Sorted the same as extraHeader.Write's loop.
660 var extraHeaderKeys
= [][]byte{
661 []byte("Content-Type"),
662 []byte("Connection"),
663 []byte("Transfer-Encoding"),
667 headerContentLength
= []byte("Content-Length: ")
668 headerDate
= []byte("Date: ")
671 // Write writes the headers described in h to w.
673 // This method has a value receiver, despite the somewhat large size
674 // of h, because it prevents an allocation. The escape analysis isn't
675 // smart enough to realize this function doesn't mutate h.
676 func (h extraHeader
) Write(w
*bufio
.Writer
) {
682 if h
.contentLength
!= nil {
683 w
.Write(headerContentLength
)
684 w
.Write(h
.contentLength
)
687 for i
, v
:= range []string{h
.contentType
, h
.connection
, h
.transferEncoding
} {
689 w
.Write(extraHeaderKeys
[i
])
697 // writeHeader finalizes the header sent to the client and writes it
698 // to cw.res.conn.buf.
700 // p is not written by writeHeader, but is the first chunk of the body
701 // that will be written. It is sniffed for a Content-Type if none is
702 // set explicitly. It's also used to set the Content-Length, if the
703 // total body size was small and the handler has already finished
705 func (cw
*chunkWriter
) writeHeader(p
[]byte) {
709 cw
.wroteHeader
= true
712 keepAlivesEnabled
:= w
.conn
.server
.doKeepAlives()
713 isHEAD
:= w
.req
.Method
== "HEAD"
715 // header is written out to w.conn.buf below. Depending on the
716 // state of the handler, we either own the map or not. If we
717 // don't own it, the exclude map is created lazily for
718 // WriteSubset to remove headers. The setHeader struct holds
719 // headers we need to add.
721 owned
:= header
!= nil
723 header
= w
.handlerHeader
725 var excludeHeader
map[string]bool
726 delHeader
:= func(key
string) {
731 if _
, ok
:= header
[key
]; !ok
{
734 if excludeHeader
== nil {
735 excludeHeader
= make(map[string]bool)
737 excludeHeader
[key
] = true
739 var setHeader extraHeader
741 // If the handler is done but never sent a Content-Length
742 // response header and this is our first (and last) write, set
743 // it, even to zero. This helps HTTP/1.0 clients keep their
744 // "keep-alive" connections alive.
745 // Exceptions: 304/204/1xx responses never get Content-Length, and if
746 // it was a HEAD request, we don't know the difference between
747 // 0 actual bytes and 0 bytes because the handler noticed it
748 // was a HEAD request and chose not to write anything. So for
749 // HEAD, the handler should either write the Content-Length or
750 // write non-zero bytes. If it's actually 0 bytes and the
751 // handler never looked at the Request.Method, we just don't
752 // send a Content-Length header.
753 if w
.handlerDone
&& bodyAllowedForStatus(w
.status
) && header
.get("Content-Length") == "" && (!isHEAD ||
len(p
) > 0) {
754 w
.contentLength
= int64(len(p
))
755 setHeader
.contentLength
= strconv
.AppendInt(cw
.res
.clenBuf
[:0], int64(len(p
)), 10)
758 // If this was an HTTP/1.0 request with keep-alive and we sent a
759 // Content-Length back, we can make this a keep-alive response ...
760 if w
.req
.wantsHttp10KeepAlive() && keepAlivesEnabled
{
761 sentLength
:= header
.get("Content-Length") != ""
762 if sentLength
&& header
.get("Connection") == "keep-alive" {
763 w
.closeAfterReply
= false
767 // Check for a explicit (and valid) Content-Length header.
768 hasCL
:= w
.contentLength
!= -1
770 if w
.req
.wantsHttp10KeepAlive() && (isHEAD || hasCL
) {
771 _
, connectionHeaderSet
:= header
["Connection"]
772 if !connectionHeaderSet
{
773 setHeader
.connection
= "keep-alive"
775 } else if !w
.req
.ProtoAtLeast(1, 1) || w
.req
.wantsClose() {
776 w
.closeAfterReply
= true
779 if header
.get("Connection") == "close" ||
!keepAlivesEnabled
{
780 w
.closeAfterReply
= true
783 // Per RFC 2616, we should consume the request body before
784 // replying, if the handler hasn't already done so. But we
785 // don't want to do an unbounded amount of reading here for
786 // DoS reasons, so we only try up to a threshold.
787 if w
.req
.ContentLength
!= 0 && !w
.closeAfterReply
{
788 ecr
, isExpecter
:= w
.req
.Body
.(*expectContinueReader
)
789 if !isExpecter || ecr
.resp
.wroteContinue
{
790 n
, _
:= io
.CopyN(ioutil
.Discard
, w
.req
.Body
, maxPostHandlerReadBytes
+1)
791 if n
>= maxPostHandlerReadBytes
{
793 delHeader("Connection")
794 setHeader
.connection
= "close"
802 if bodyAllowedForStatus(code
) {
803 // If no content type, apply sniffing algorithm to body.
804 _
, haveType
:= header
["Content-Type"]
806 setHeader
.contentType
= DetectContentType(p
)
809 for _
, k
:= range suppressedHeaders(code
) {
814 if _
, ok
:= header
["Date"]; !ok
{
815 setHeader
.date
= appendTime(cw
.res
.dateBuf
[:0], time
.Now())
818 te
:= header
.get("Transfer-Encoding")
820 if hasCL
&& hasTE
&& te
!= "identity" {
821 // TODO: return an error if WriteHeader gets a return parameter
822 // For now just ignore the Content-Length.
823 w
.conn
.server
.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
825 delHeader("Content-Length")
829 if w
.req
.Method
== "HEAD" ||
!bodyAllowedForStatus(code
) {
831 } else if code
== StatusNoContent
{
832 delHeader("Transfer-Encoding")
834 delHeader("Transfer-Encoding")
835 } else if w
.req
.ProtoAtLeast(1, 1) {
836 // HTTP/1.1 or greater: use chunked transfer encoding
837 // to avoid closing the connection at EOF.
838 // TODO: this blows away any custom or stacked Transfer-Encoding they
839 // might have set. Deal with that as need arises once we have a valid
842 setHeader
.transferEncoding
= "chunked"
844 // HTTP version < 1.1: cannot do chunked transfer
845 // encoding and we don't know the Content-Length so
846 // signal EOF by closing connection.
847 w
.closeAfterReply
= true
848 delHeader("Transfer-Encoding") // in case already set
851 // Cannot use Content-Length with non-identity Transfer-Encoding.
853 delHeader("Content-Length")
855 if !w
.req
.ProtoAtLeast(1, 0) {
859 if w
.closeAfterReply
&& (!keepAlivesEnabled ||
!hasToken(cw
.header
.get("Connection"), "close")) {
860 delHeader("Connection")
861 if w
.req
.ProtoAtLeast(1, 1) {
862 setHeader
.connection
= "close"
866 w
.conn
.buf
.WriteString(statusLine(w
.req
, code
))
867 cw
.header
.WriteSubset(w
.conn
.buf
, excludeHeader
)
868 setHeader
.Write(w
.conn
.buf
.Writer
)
869 w
.conn
.buf
.Write(crlf
)
872 // statusLines is a cache of Status-Line strings, keyed by code (for
873 // HTTP/1.1) or negative code (for HTTP/1.0). This is faster than a
874 // map keyed by struct of two fields. This map's max size is bounded
875 // by 2*len(statusText), two protocol types for each known official
876 // status code in the statusText map.
878 statusMu sync
.RWMutex
879 statusLines
= make(map[int]string)
882 // statusLine returns a response Status-Line (RFC 2616 Section 6.1)
883 // for the given request and response status code.
884 func statusLine(req
*Request
, code
int) string {
887 proto11
:= req
.ProtoAtLeast(1, 1)
892 line
, ok
:= statusLines
[key
]
903 codestring
:= strconv
.Itoa(code
)
904 text
, ok
:= statusText
[code
]
906 text
= "status code " + codestring
908 line
= proto
+ " " + codestring
+ " " + text
+ "\r\n"
911 defer statusMu
.Unlock()
912 statusLines
[key
] = line
917 // bodyAllowed returns true if a Write is allowed for this response type.
918 // It's illegal to call this before the header has been flushed.
919 func (w
*response
) bodyAllowed() bool {
923 return bodyAllowedForStatus(w
.status
)
926 // The Life Of A Write is like this:
928 // Handler starts. No header has been sent. The handler can either
929 // write a header, or just start writing. Writing before sending a header
930 // sends an implicitly empty 200 OK header.
932 // If the handler didn't declare a Content-Length up front, we either
933 // go into chunking mode or, if the handler finishes running before
934 // the chunking buffer size, we compute a Content-Length and send that
935 // in the header instead.
937 // Likewise, if the handler didn't set a Content-Type, we sniff that
938 // from the initial chunk of output.
940 // The Writers are wired together like:
942 // 1. *response (the ResponseWriter) ->
943 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
944 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
945 // and which writes the chunk headers, if needed.
946 // 4. conn.buf, a bufio.Writer of default (4kB) bytes
947 // 5. the rwc, the net.Conn.
949 // TODO(bradfitz): short-circuit some of the buffering when the
950 // initial header contains both a Content-Type and Content-Length.
951 // Also short-circuit in (1) when the header's been sent and not in
952 // chunking mode, writing directly to (4) instead, if (2) has no
953 // buffered data. More generally, we could short-circuit from (1) to
954 // (3) even in chunking mode if the write size from (1) is over some
955 // threshold and nothing is in (2). The answer might be mostly making
956 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
957 // with this instead.
958 func (w
*response
) Write(data
[]byte) (n
int, err error
) {
959 return w
.write(len(data
), data
, "")
962 func (w
*response
) WriteString(data
string) (n
int, err error
) {
963 return w
.write(len(data
), nil, data
)
966 // either dataB or dataS is non-zero.
967 func (w
*response
) write(lenData
int, dataB
[]byte, dataS
string) (n
int, err error
) {
968 if w
.conn
.hijacked() {
969 w
.conn
.server
.logf("http: response.Write on hijacked connection")
970 return 0, ErrHijacked
973 w
.WriteHeader(StatusOK
)
978 if !w
.bodyAllowed() {
979 return 0, ErrBodyNotAllowed
982 w
.written
+= int64(lenData
) // ignoring errors, for errorKludge
983 if w
.contentLength
!= -1 && w
.written
> w
.contentLength
{
984 return 0, ErrContentLength
987 return w
.w
.Write(dataB
)
989 return w
.w
.WriteString(dataS
)
993 func (w
*response
) finishRequest() {
997 w
.WriteHeader(StatusOK
)
1005 // Close the body (regardless of w.closeAfterReply) so we can
1006 // re-use its bufio.Reader later safely.
1009 if w
.req
.MultipartForm
!= nil {
1010 w
.req
.MultipartForm
.RemoveAll()
1013 if w
.req
.Method
!= "HEAD" && w
.contentLength
!= -1 && w
.bodyAllowed() && w
.contentLength
!= w
.written
{
1014 // Did not write enough. Avoid getting out of sync.
1015 w
.closeAfterReply
= true
1019 func (w
*response
) Flush() {
1021 w
.WriteHeader(StatusOK
)
1027 func (c
*conn
) finalFlush() {
1031 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1032 // reader for a future connection.
1033 putBufioReader(c
.buf
.Reader
)
1035 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1036 // writer for a future connection.
1037 putBufioWriter(c
.buf
.Writer
)
1043 // Close the connection.
1044 func (c
*conn
) close() {
1052 // rstAvoidanceDelay is the amount of time we sleep after closing the
1053 // write side of a TCP connection before closing the entire socket.
1054 // By sleeping, we increase the chances that the client sees our FIN
1055 // and processes its final data before they process the subsequent RST
1056 // from closing a connection with known unread data.
1057 // This RST seems to occur mostly on BSD systems. (And Windows?)
1058 // This timeout is somewhat arbitrary (~latency around the planet).
1059 const rstAvoidanceDelay
= 500 * time
.Millisecond
1061 // closeWrite flushes any outstanding data and sends a FIN packet (if
1062 // client is connected via TCP), signalling that we're done. We then
1063 // pause for a bit, hoping the client processes it before `any
1066 // See http://golang.org/issue/3595
1067 func (c
*conn
) closeWriteAndWait() {
1069 if tcp
, ok
:= c
.rwc
.(*net
.TCPConn
); ok
{
1072 time
.Sleep(rstAvoidanceDelay
)
1075 // validNPN reports whether the proto is not a blacklisted Next
1076 // Protocol Negotiation protocol. Empty and built-in protocol types
1077 // are blacklisted and can't be overridden with alternate
1079 func validNPN(proto
string) bool {
1081 case "", "http/1.1", "http/1.0":
1087 func (c
*conn
) setState(nc net
.Conn
, state ConnState
) {
1088 if hook
:= c
.server
.ConnState
; hook
!= nil {
1093 // Serve a new connection.
1094 func (c
*conn
) serve() {
1095 origConn
:= c
.rwc
// copy it before it's set nil on Close or Hijack
1097 if err
:= recover(); err
!= nil {
1098 const size
= 64 << 10
1099 buf
:= make([]byte, size
)
1100 buf
= buf
[:runtime
.Stack(buf
, false)]
1101 c
.server
.logf("http: panic serving %v: %v\n%s", c
.remoteAddr
, err
, buf
)
1105 c
.setState(origConn
, StateClosed
)
1109 if tlsConn
, ok
:= c
.rwc
.(*tls
.Conn
); ok
{
1110 if d
:= c
.server
.ReadTimeout
; d
!= 0 {
1111 c
.rwc
.SetReadDeadline(time
.Now().Add(d
))
1113 if d
:= c
.server
.WriteTimeout
; d
!= 0 {
1114 c
.rwc
.SetWriteDeadline(time
.Now().Add(d
))
1116 if err
:= tlsConn
.Handshake(); err
!= nil {
1117 c
.server
.logf("http: TLS handshake error from %s: %v", c
.rwc
.RemoteAddr(), err
)
1120 c
.tlsState
= new(tls
.ConnectionState
)
1121 *c
.tlsState
= tlsConn
.ConnectionState()
1122 if proto
:= c
.tlsState
.NegotiatedProtocol
; validNPN(proto
) {
1123 if fn
:= c
.server
.TLSNextProto
[proto
]; fn
!= nil {
1124 h
:= initNPNRequest
{tlsConn
, serverHandler
{c
.server
}}
1125 fn(c
.server
, tlsConn
, h
)
1132 w
, err
:= c
.readRequest()
1133 if c
.lr
.N
!= c
.server
.initialLimitedReaderSize() {
1134 // If we read any bytes off the wire, we're active.
1135 c
.setState(c
.rwc
, StateActive
)
1138 if err
== errTooLarge
{
1139 // Their HTTP client may or may not be
1140 // able to read this if we're
1141 // responding to them and hanging up
1142 // while they're still writing their
1143 // request. Undefined behavior.
1144 io
.WriteString(c
.rwc
, "HTTP/1.1 413 Request Entity Too Large\r\n\r\n")
1145 c
.closeWriteAndWait()
1147 } else if err
== io
.EOF
{
1148 break // Don't reply
1149 } else if neterr
, ok
:= err
.(net
.Error
); ok
&& neterr
.Timeout() {
1150 break // Don't reply
1152 io
.WriteString(c
.rwc
, "HTTP/1.1 400 Bad Request\r\n\r\n")
1156 // Expect 100 Continue support
1158 if req
.expectsContinue() {
1159 if req
.ProtoAtLeast(1, 1) && req
.ContentLength
!= 0 {
1160 // Wrap the Body reader with one that replies on the connection
1161 req
.Body
= &expectContinueReader
{readCloser
: req
.Body
, resp
: w
}
1163 req
.Header
.Del("Expect")
1164 } else if req
.Header
.get("Expect") != "" {
1165 w
.sendExpectationFailed()
1169 // HTTP cannot have multiple simultaneous active requests.[*]
1170 // Until the server replies to this request, it can't read another,
1171 // so we might as well run the handler in this goroutine.
1172 // [*] Not strictly true: HTTP pipelining. We could let them all process
1173 // in parallel even if their responses need to be serialized.
1174 serverHandler
{c
.server
}.ServeHTTP(w
, w
.req
)
1179 if w
.closeAfterReply
{
1180 if w
.requestBodyLimitHit
{
1181 c
.closeWriteAndWait()
1185 c
.setState(c
.rwc
, StateIdle
)
1189 func (w
*response
) sendExpectationFailed() {
1190 // TODO(bradfitz): let ServeHTTP handlers handle
1191 // requests with non-standard expectation[s]? Seems
1192 // theoretical at best, and doesn't fit into the
1193 // current ServeHTTP model anyway. We'd need to
1194 // make the ResponseWriter an optional
1195 // "ExpectReplier" interface or something.
1197 // For now we'll just obey RFC 2616 14.20 which says
1198 // "If a server receives a request containing an
1199 // Expect field that includes an expectation-
1200 // extension that it does not support, it MUST
1201 // respond with a 417 (Expectation Failed) status."
1202 w
.Header().Set("Connection", "close")
1203 w
.WriteHeader(StatusExpectationFailed
)
1207 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
1209 func (w
*response
) Hijack() (rwc net
.Conn
, buf
*bufio
.ReadWriter
, err error
) {
1213 // Release the bufioWriter that writes to the chunk writer, it is not
1214 // used after a connection has been hijacked.
1215 rwc
, buf
, err
= w
.conn
.hijack()
1220 return rwc
, buf
, err
1223 func (w
*response
) CloseNotify() <-chan bool {
1224 return w
.conn
.closeNotify()
1227 // The HandlerFunc type is an adapter to allow the use of
1228 // ordinary functions as HTTP handlers. If f is a function
1229 // with the appropriate signature, HandlerFunc(f) is a
1230 // Handler object that calls f.
1231 type HandlerFunc
func(ResponseWriter
, *Request
)
1233 // ServeHTTP calls f(w, r).
1234 func (f HandlerFunc
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1240 // Error replies to the request with the specified error message and HTTP code.
1241 // The error message should be plain text.
1242 func Error(w ResponseWriter
, error
string, code
int) {
1243 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
1245 fmt
.Fprintln(w
, error
)
1248 // NotFound replies to the request with an HTTP 404 not found error.
1249 func NotFound(w ResponseWriter
, r
*Request
) { Error(w
, "404 page not found", StatusNotFound
) }
1251 // NotFoundHandler returns a simple request handler
1252 // that replies to each request with a ``404 page not found'' reply.
1253 func NotFoundHandler() Handler
{ return HandlerFunc(NotFound
) }
1255 // StripPrefix returns a handler that serves HTTP requests
1256 // by removing the given prefix from the request URL's Path
1257 // and invoking the handler h. StripPrefix handles a
1258 // request for a path that doesn't begin with prefix by
1259 // replying with an HTTP 404 not found error.
1260 func StripPrefix(prefix
string, h Handler
) Handler
{
1264 return HandlerFunc(func(w ResponseWriter
, r
*Request
) {
1265 if p
:= strings
.TrimPrefix(r
.URL
.Path
, prefix
); len(p
) < len(r
.URL
.Path
) {
1274 // Redirect replies to the request with a redirect to url,
1275 // which may be a path relative to the request path.
1276 func Redirect(w ResponseWriter
, r
*Request
, urlStr
string, code
int) {
1277 if u
, err
:= url
.Parse(urlStr
); err
== nil {
1278 // If url was relative, make absolute by
1279 // combining with request path.
1280 // The browser would probably do this for us,
1281 // but doing it ourselves is more reliable.
1283 // NOTE(rsc): RFC 2616 says that the Location
1284 // line must be an absolute URI, like
1285 // "http://www.google.com/redirect/",
1286 // not a path like "/redirect/".
1287 // Unfortunately, we don't know what to
1288 // put in the host name section to get the
1289 // client to connect to us again, so we can't
1290 // know the right absolute URI to send back.
1291 // Because of this problem, no one pays attention
1292 // to the RFC; they all send back just a new path.
1294 oldpath
:= r
.URL
.Path
1295 if oldpath
== "" { // should not happen, but avoid a crash if it does
1299 // no leading http://server
1300 if urlStr
== "" || urlStr
[0] != '/' {
1301 // make relative path absolute
1302 olddir
, _
:= path
.Split(oldpath
)
1303 urlStr
= olddir
+ urlStr
1307 if i
:= strings
.Index(urlStr
, "?"); i
!= -1 {
1308 urlStr
, query
= urlStr
[:i
], urlStr
[i
:]
1311 // clean up but preserve trailing slash
1312 trailing
:= strings
.HasSuffix(urlStr
, "/")
1313 urlStr
= path
.Clean(urlStr
)
1314 if trailing
&& !strings
.HasSuffix(urlStr
, "/") {
1321 w
.Header().Set("Location", urlStr
)
1324 // RFC2616 recommends that a short note "SHOULD" be included in the
1325 // response because older user agents may not understand 301/307.
1326 // Shouldn't send the response for POST or HEAD; that leaves GET.
1327 if r
.Method
== "GET" {
1328 note
:= "<a href=\"" + htmlEscape(urlStr
) + "\">" + statusText
[code
] + "</a>.\n"
1329 fmt
.Fprintln(w
, note
)
1333 var htmlReplacer
= strings
.NewReplacer(
1337 // """ is shorter than """.
1339 // "'" is shorter than "'" and apos was not in HTML until HTML5.
1343 func htmlEscape(s
string) string {
1344 return htmlReplacer
.Replace(s
)
1347 // Redirect to a fixed URL
1348 type redirectHandler
struct {
1353 func (rh
*redirectHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1354 Redirect(w
, r
, rh
.url
, rh
.code
)
1357 // RedirectHandler returns a request handler that redirects
1358 // each request it receives to the given url using the given
1360 func RedirectHandler(url
string, code
int) Handler
{
1361 return &redirectHandler
{url
, code
}
1364 // ServeMux is an HTTP request multiplexer.
1365 // It matches the URL of each incoming request against a list of registered
1366 // patterns and calls the handler for the pattern that
1367 // most closely matches the URL.
1369 // Patterns name fixed, rooted paths, like "/favicon.ico",
1370 // or rooted subtrees, like "/images/" (note the trailing slash).
1371 // Longer patterns take precedence over shorter ones, so that
1372 // if there are handlers registered for both "/images/"
1373 // and "/images/thumbnails/", the latter handler will be
1374 // called for paths beginning "/images/thumbnails/" and the
1375 // former will receive requests for any other paths in the
1376 // "/images/" subtree.
1378 // Note that since a pattern ending in a slash names a rooted subtree,
1379 // the pattern "/" matches all paths not matched by other registered
1380 // patterns, not just the URL with Path == "/".
1382 // Patterns may optionally begin with a host name, restricting matches to
1383 // URLs on that host only. Host-specific patterns take precedence over
1384 // general patterns, so that a handler might register for the two patterns
1385 // "/codesearch" and "codesearch.google.com/" without also taking over
1386 // requests for "http://www.google.com/".
1388 // ServeMux also takes care of sanitizing the URL request path,
1389 // redirecting any request containing . or .. elements to an
1390 // equivalent .- and ..-free URL.
1391 type ServeMux
struct {
1393 m
map[string]muxEntry
1394 hosts
bool // whether any patterns contain hostnames
1397 type muxEntry
struct {
1403 // NewServeMux allocates and returns a new ServeMux.
1404 func NewServeMux() *ServeMux
{ return &ServeMux
{m
: make(map[string]muxEntry
)} }
1406 // DefaultServeMux is the default ServeMux used by Serve.
1407 var DefaultServeMux
= NewServeMux()
1409 // Does path match pattern?
1410 func pathMatch(pattern
, path
string) bool {
1411 if len(pattern
) == 0 {
1412 // should not happen
1416 if pattern
[n
-1] != '/' {
1417 return pattern
== path
1419 return len(path
) >= n
&& path
[0:n
] == pattern
1422 // Return the canonical path for p, eliminating . and .. elements.
1423 func cleanPath(p
string) string {
1431 // path.Clean removes trailing slash except for root;
1432 // put the trailing slash back if necessary.
1433 if p
[len(p
)-1] == '/' && np
!= "/" {
1439 // Find a handler on a handler map given a path string
1440 // Most-specific (longest) pattern wins
1441 func (mux
*ServeMux
) match(path
string) (h Handler
, pattern
string) {
1443 for k
, v
:= range mux
.m
{
1444 if !pathMatch(k
, path
) {
1447 if h
== nil ||
len(k
) > n
{
1456 // Handler returns the handler to use for the given request,
1457 // consulting r.Method, r.Host, and r.URL.Path. It always returns
1458 // a non-nil handler. If the path is not in its canonical form, the
1459 // handler will be an internally-generated handler that redirects
1460 // to the canonical path.
1462 // Handler also returns the registered pattern that matches the
1463 // request or, in the case of internally-generated redirects,
1464 // the pattern that will match after following the redirect.
1466 // If there is no registered handler that applies to the request,
1467 // Handler returns a ``page not found'' handler and an empty pattern.
1468 func (mux
*ServeMux
) Handler(r
*Request
) (h Handler
, pattern
string) {
1469 if r
.Method
!= "CONNECT" {
1470 if p
:= cleanPath(r
.URL
.Path
); p
!= r
.URL
.Path
{
1471 _
, pattern
= mux
.handler(r
.Host
, p
)
1474 return RedirectHandler(url
.String(), StatusMovedPermanently
), pattern
1478 return mux
.handler(r
.Host
, r
.URL
.Path
)
1481 // handler is the main implementation of Handler.
1482 // The path is known to be in canonical form, except for CONNECT methods.
1483 func (mux
*ServeMux
) handler(host
, path
string) (h Handler
, pattern
string) {
1485 defer mux
.mu
.RUnlock()
1487 // Host-specific pattern takes precedence over generic ones
1489 h
, pattern
= mux
.match(host
+ path
)
1492 h
, pattern
= mux
.match(path
)
1495 h
, pattern
= NotFoundHandler(), ""
1500 // ServeHTTP dispatches the request to the handler whose
1501 // pattern most closely matches the request URL.
1502 func (mux
*ServeMux
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1503 if r
.RequestURI
== "*" {
1504 if r
.ProtoAtLeast(1, 1) {
1505 w
.Header().Set("Connection", "close")
1507 w
.WriteHeader(StatusBadRequest
)
1510 h
, _
:= mux
.Handler(r
)
1514 // Handle registers the handler for the given pattern.
1515 // If a handler already exists for pattern, Handle panics.
1516 func (mux
*ServeMux
) Handle(pattern
string, handler Handler
) {
1518 defer mux
.mu
.Unlock()
1521 panic("http: invalid pattern " + pattern
)
1524 panic("http: nil handler")
1526 if mux
.m
[pattern
].explicit
{
1527 panic("http: multiple registrations for " + pattern
)
1530 mux
.m
[pattern
] = muxEntry
{explicit
: true, h
: handler
, pattern
: pattern
}
1532 if pattern
[0] != '/' {
1536 // Helpful behavior:
1537 // If pattern is /tree/, insert an implicit permanent redirect for /tree.
1538 // It can be overridden by an explicit registration.
1540 if n
> 0 && pattern
[n
-1] == '/' && !mux
.m
[pattern
[0:n
-1]].explicit
{
1541 // If pattern contains a host name, strip it and use remaining
1542 // path for redirect.
1544 if pattern
[0] != '/' {
1545 // In pattern, at least the last character is a '/', so
1546 // strings.Index can't be -1.
1547 path
= pattern
[strings
.Index(pattern
, "/"):]
1549 mux
.m
[pattern
[0:n
-1]] = muxEntry
{h
: RedirectHandler(path
, StatusMovedPermanently
), pattern
: pattern
}
1553 // HandleFunc registers the handler function for the given pattern.
1554 func (mux
*ServeMux
) HandleFunc(pattern
string, handler
func(ResponseWriter
, *Request
)) {
1555 mux
.Handle(pattern
, HandlerFunc(handler
))
1558 // Handle registers the handler for the given pattern
1559 // in the DefaultServeMux.
1560 // The documentation for ServeMux explains how patterns are matched.
1561 func Handle(pattern
string, handler Handler
) { DefaultServeMux
.Handle(pattern
, handler
) }
1563 // HandleFunc registers the handler function for the given pattern
1564 // in the DefaultServeMux.
1565 // The documentation for ServeMux explains how patterns are matched.
1566 func HandleFunc(pattern
string, handler
func(ResponseWriter
, *Request
)) {
1567 DefaultServeMux
.HandleFunc(pattern
, handler
)
1570 // Serve accepts incoming HTTP connections on the listener l,
1571 // creating a new service goroutine for each. The service goroutines
1572 // read requests and then call handler to reply to them.
1573 // Handler is typically nil, in which case the DefaultServeMux is used.
1574 func Serve(l net
.Listener
, handler Handler
) error
{
1575 srv
:= &Server
{Handler
: handler
}
1579 // A Server defines parameters for running an HTTP server.
1580 // The zero value for Server is a valid configuration.
1581 type Server
struct {
1582 Addr
string // TCP address to listen on, ":http" if empty
1583 Handler Handler
// handler to invoke, http.DefaultServeMux if nil
1584 ReadTimeout time
.Duration
// maximum duration before timing out read of the request
1585 WriteTimeout time
.Duration
// maximum duration before timing out write of the response
1586 MaxHeaderBytes
int // maximum size of request headers, DefaultMaxHeaderBytes if 0
1587 TLSConfig
*tls
.Config
// optional TLS config, used by ListenAndServeTLS
1589 // TLSNextProto optionally specifies a function to take over
1590 // ownership of the provided TLS connection when an NPN
1591 // protocol upgrade has occurred. The map key is the protocol
1592 // name negotiated. The Handler argument should be used to
1593 // handle HTTP requests and will initialize the Request's TLS
1594 // and RemoteAddr if not already set. The connection is
1595 // automatically closed when the function returns.
1596 TLSNextProto
map[string]func(*Server
, *tls
.Conn
, Handler
)
1598 // ConnState specifies an optional callback function that is
1599 // called when a client connection changes state. See the
1600 // ConnState type and associated constants for details.
1601 ConnState
func(net
.Conn
, ConnState
)
1603 // ErrorLog specifies an optional logger for errors accepting
1604 // connections and unexpected behavior from handlers.
1605 // If nil, logging goes to os.Stderr via the log package's
1607 ErrorLog
*log
.Logger
1609 disableKeepAlives
int32 // accessed atomically.
1612 // A ConnState represents the state of a client connection to a server.
1613 // It's used by the optional Server.ConnState hook.
1617 // StateNew represents a new connection that is expected to
1618 // send a request immediately. Connections begin at this
1619 // state and then transition to either StateActive or
1621 StateNew ConnState
= iota
1623 // StateActive represents a connection that has read 1 or more
1624 // bytes of a request. The Server.ConnState hook for
1625 // StateActive fires before the request has entered a handler
1626 // and doesn't fire again until the request has been
1627 // handled. After the request is handled, the state
1628 // transitions to StateClosed, StateHijacked, or StateIdle.
1631 // StateIdle represents a connection that has finished
1632 // handling a request and is in the keep-alive state, waiting
1633 // for a new request. Connections transition from StateIdle
1634 // to either StateActive or StateClosed.
1637 // StateHijacked represents a hijacked connection.
1638 // This is a terminal state. It does not transition to StateClosed.
1641 // StateClosed represents a closed connection.
1642 // This is a terminal state. Hijacked connections do not
1643 // transition to StateClosed.
1647 var stateName
= map[ConnState
]string{
1649 StateActive
: "active",
1651 StateHijacked
: "hijacked",
1652 StateClosed
: "closed",
1655 func (c ConnState
) String() string {
1659 // serverHandler delegates to either the server's Handler or
1660 // DefaultServeMux and also handles "OPTIONS *" requests.
1661 type serverHandler
struct {
1665 func (sh serverHandler
) ServeHTTP(rw ResponseWriter
, req
*Request
) {
1666 handler
:= sh
.srv
.Handler
1668 handler
= DefaultServeMux
1670 if req
.RequestURI
== "*" && req
.Method
== "OPTIONS" {
1671 handler
= globalOptionsHandler
{}
1673 handler
.ServeHTTP(rw
, req
)
1676 // ListenAndServe listens on the TCP network address srv.Addr and then
1677 // calls Serve to handle requests on incoming connections. If
1678 // srv.Addr is blank, ":http" is used.
1679 func (srv
*Server
) ListenAndServe() error
{
1684 ln
, err
:= net
.Listen("tcp", addr
)
1688 return srv
.Serve(tcpKeepAliveListener
{ln
.(*net
.TCPListener
)})
1691 // Serve accepts incoming connections on the Listener l, creating a
1692 // new service goroutine for each. The service goroutines read requests and
1693 // then call srv.Handler to reply to them.
1694 func (srv
*Server
) Serve(l net
.Listener
) error
{
1696 var tempDelay time
.Duration
// how long to sleep on accept failure
1700 if ne
, ok
:= e
.(net
.Error
); ok
&& ne
.Temporary() {
1702 tempDelay
= 5 * time
.Millisecond
1706 if max
:= 1 * time
.Second
; tempDelay
> max
{
1709 srv
.logf("http: Accept error: %v; retrying in %v", e
, tempDelay
)
1710 time
.Sleep(tempDelay
)
1716 c
, err
:= srv
.newConn(rw
)
1720 c
.setState(c
.rwc
, StateNew
) // before Serve can return
1725 func (s
*Server
) doKeepAlives() bool {
1726 return atomic
.LoadInt32(&s
.disableKeepAlives
) == 0
1729 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
1730 // By default, keep-alives are always enabled. Only very
1731 // resource-constrained environments or servers in the process of
1732 // shutting down should disable them.
1733 func (s
*Server
) SetKeepAlivesEnabled(v
bool) {
1735 atomic
.StoreInt32(&s
.disableKeepAlives
, 0)
1737 atomic
.StoreInt32(&s
.disableKeepAlives
, 1)
1741 func (s
*Server
) logf(format
string, args
...interface{}) {
1742 if s
.ErrorLog
!= nil {
1743 s
.ErrorLog
.Printf(format
, args
...)
1745 log
.Printf(format
, args
...)
1749 // ListenAndServe listens on the TCP network address addr
1750 // and then calls Serve with handler to handle requests
1751 // on incoming connections. Handler is typically nil,
1752 // in which case the DefaultServeMux is used.
1754 // A trivial example server is:
1764 // // hello world, the web server
1765 // func HelloServer(w http.ResponseWriter, req *http.Request) {
1766 // io.WriteString(w, "hello, world!\n")
1770 // http.HandleFunc("/hello", HelloServer)
1771 // err := http.ListenAndServe(":12345", nil)
1773 // log.Fatal("ListenAndServe: ", err)
1776 func ListenAndServe(addr
string, handler Handler
) error
{
1777 server
:= &Server
{Addr
: addr
, Handler
: handler
}
1778 return server
.ListenAndServe()
1781 // ListenAndServeTLS acts identically to ListenAndServe, except that it
1782 // expects HTTPS connections. Additionally, files containing a certificate and
1783 // matching private key for the server must be provided. If the certificate
1784 // is signed by a certificate authority, the certFile should be the concatenation
1785 // of the server's certificate followed by the CA's certificate.
1787 // A trivial example server is:
1794 // func handler(w http.ResponseWriter, req *http.Request) {
1795 // w.Header().Set("Content-Type", "text/plain")
1796 // w.Write([]byte("This is an example server.\n"))
1800 // http.HandleFunc("/", handler)
1801 // log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
1802 // err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
1808 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
1809 func ListenAndServeTLS(addr
string, certFile
string, keyFile
string, handler Handler
) error
{
1810 server
:= &Server
{Addr
: addr
, Handler
: handler
}
1811 return server
.ListenAndServeTLS(certFile
, keyFile
)
1814 // ListenAndServeTLS listens on the TCP network address srv.Addr and
1815 // then calls Serve to handle requests on incoming TLS connections.
1817 // Filenames containing a certificate and matching private key for
1818 // the server must be provided. If the certificate is signed by a
1819 // certificate authority, the certFile should be the concatenation
1820 // of the server's certificate followed by the CA's certificate.
1822 // If srv.Addr is blank, ":https" is used.
1823 func (srv
*Server
) ListenAndServeTLS(certFile
, keyFile
string) error
{
1828 config
:= &tls
.Config
{}
1829 if srv
.TLSConfig
!= nil {
1830 *config
= *srv
.TLSConfig
1832 if config
.NextProtos
== nil {
1833 config
.NextProtos
= []string{"http/1.1"}
1837 config
.Certificates
= make([]tls
.Certificate
, 1)
1838 config
.Certificates
[0], err
= tls
.LoadX509KeyPair(certFile
, keyFile
)
1843 ln
, err
:= net
.Listen("tcp", addr
)
1848 tlsListener
:= tls
.NewListener(tcpKeepAliveListener
{ln
.(*net
.TCPListener
)}, config
)
1849 return srv
.Serve(tlsListener
)
1852 // TimeoutHandler returns a Handler that runs h with the given time limit.
1854 // The new Handler calls h.ServeHTTP to handle each request, but if a
1855 // call runs for longer than its time limit, the handler responds with
1856 // a 503 Service Unavailable error and the given message in its body.
1857 // (If msg is empty, a suitable default message will be sent.)
1858 // After such a timeout, writes by h to its ResponseWriter will return
1859 // ErrHandlerTimeout.
1860 func TimeoutHandler(h Handler
, dt time
.Duration
, msg
string) Handler
{
1861 f
:= func() <-chan time
.Time
{
1862 return time
.After(dt
)
1864 return &timeoutHandler
{h
, f
, msg
}
1867 // ErrHandlerTimeout is returned on ResponseWriter Write calls
1868 // in handlers which have timed out.
1869 var ErrHandlerTimeout
= errors
.New("http: Handler timeout")
1871 type timeoutHandler
struct {
1873 timeout
func() <-chan time
.Time
// returns channel producing a timeout
1877 func (h
*timeoutHandler
) errorBody() string {
1881 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
1884 func (h
*timeoutHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1885 done
:= make(chan bool, 1)
1886 tw
:= &timeoutWriter
{w
: w
}
1888 h
.handler
.ServeHTTP(tw
, r
)
1896 defer tw
.mu
.Unlock()
1897 if !tw
.wroteHeader
{
1898 tw
.w
.WriteHeader(StatusServiceUnavailable
)
1899 tw
.w
.Write([]byte(h
.errorBody()))
1905 type timeoutWriter
struct {
1913 func (tw
*timeoutWriter
) Header() Header
{
1914 return tw
.w
.Header()
1917 func (tw
*timeoutWriter
) Write(p
[]byte) (int, error
) {
1919 timedOut
:= tw
.timedOut
1922 return 0, ErrHandlerTimeout
1924 return tw
.w
.Write(p
)
1927 func (tw
*timeoutWriter
) WriteHeader(code
int) {
1929 if tw
.timedOut || tw
.wroteHeader
{
1933 tw
.wroteHeader
= true
1935 tw
.w
.WriteHeader(code
)
1938 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
1939 // connections. It's used by ListenAndServe and ListenAndServeTLS so
1940 // dead TCP connections (e.g. closing laptop mid-download) eventually
1942 type tcpKeepAliveListener
struct {
1946 func (ln tcpKeepAliveListener
) Accept() (c net
.Conn
, err error
) {
1947 tc
, err
:= ln
.AcceptTCP()
1951 tc
.SetKeepAlive(true)
1952 tc
.SetKeepAlivePeriod(3 * time
.Minute
)
1956 // globalOptionsHandler responds to "OPTIONS *" requests.
1957 type globalOptionsHandler
struct{}
1959 func (globalOptionsHandler
) ServeHTTP(w ResponseWriter
, r
*Request
) {
1960 w
.Header().Set("Content-Length", "0")
1961 if r
.ContentLength
!= 0 {
1962 // Read up to 4KB of OPTIONS body (as mentioned in the
1963 // spec as being reserved for future use), but anything
1964 // over that is considered a waste of server resources
1965 // (or an attack) and we abort and close the connection,
1966 // courtesy of MaxBytesReader's EOF behavior.
1967 mb
:= MaxBytesReader(w
, r
.Body
, 4<<10)
1968 io
.Copy(ioutil
.Discard
, mb
)
1972 type eofReaderWithWriteTo
struct{}
1974 func (eofReaderWithWriteTo
) WriteTo(io
.Writer
) (int64, error
) { return 0, nil }
1975 func (eofReaderWithWriteTo
) Read([]byte) (int, error
) { return 0, io
.EOF
}
1977 // eofReader is a non-nil io.ReadCloser that always returns EOF.
1978 // It has a WriteTo method so io.Copy won't need a buffer.
1979 var eofReader
= &struct {
1980 eofReaderWithWriteTo
1983 eofReaderWithWriteTo
{},
1984 ioutil
.NopCloser(nil),
1987 // Verify that an io.Copy from an eofReader won't require a buffer.
1988 var _ io
.WriterTo
= eofReader
1990 // initNPNRequest is an HTTP handler that initializes certain
1991 // uninitialized fields in its *Request. Such partially-initialized
1992 // Requests come from NPN protocol handlers.
1993 type initNPNRequest
struct {
1998 func (h initNPNRequest
) ServeHTTP(rw ResponseWriter
, req
*Request
) {
2000 req
.TLS
= &tls
.ConnectionState
{}
2001 *req
.TLS
= h
.c
.ConnectionState()
2003 if req
.Body
== nil {
2004 req
.Body
= eofReader
2006 if req
.RemoteAddr
== "" {
2007 req
.RemoteAddr
= h
.c
.RemoteAddr().String()
2009 h
.h
.ServeHTTP(rw
, req
)
2012 // loggingConn is used for debugging.
2013 type loggingConn
struct {
2019 uniqNameMu sync
.Mutex
2020 uniqNameNext
= make(map[string]int)
2023 func newLoggingConn(baseName
string, c net
.Conn
) net
.Conn
{
2025 defer uniqNameMu
.Unlock()
2026 uniqNameNext
[baseName
]++
2027 return &loggingConn
{
2028 name
: fmt
.Sprintf("%s-%d", baseName
, uniqNameNext
[baseName
]),
2033 func (c
*loggingConn
) Write(p
[]byte) (n
int, err error
) {
2034 log
.Printf("%s.Write(%d) = ....", c
.name
, len(p
))
2035 n
, err
= c
.Conn
.Write(p
)
2036 log
.Printf("%s.Write(%d) = %d, %v", c
.name
, len(p
), n
, err
)
2040 func (c
*loggingConn
) Read(p
[]byte) (n
int, err error
) {
2041 log
.Printf("%s.Read(%d) = ....", c
.name
, len(p
))
2042 n
, err
= c
.Conn
.Read(p
)
2043 log
.Printf("%s.Read(%d) = %d, %v", c
.name
, len(p
), n
, err
)
2047 func (c
*loggingConn
) Close() (err error
) {
2048 log
.Printf("%s.Close() = ...", c
.name
)
2049 err
= c
.Conn
.Close()
2050 log
.Printf("%s.Close() = %v", c
.name
, err
)