libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / net / http / server.go
blob7ebd8575f3beb7d1640b14451e8c0cfb12fe2aa1
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.
7 package http
9 import (
10 "bufio"
11 "crypto/tls"
12 "errors"
13 "fmt"
14 "io"
15 "io/ioutil"
16 "log"
17 "net"
18 "net/url"
19 "os"
20 "path"
21 "runtime"
22 "strconv"
23 "strings"
24 "sync"
25 "time"
28 // Errors introduced by the HTTP server.
29 var (
30 ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
31 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
32 ErrHijacked = errors.New("Conn has been hijacked")
33 ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length")
36 // Objects implementing the Handler interface can be
37 // registered to serve a particular path or subtree
38 // in the HTTP server.
40 // ServeHTTP should write reply headers and data to the ResponseWriter
41 // and then return. Returning signals that the request is finished
42 // and that the HTTP server can move on to the next request on
43 // the connection.
44 type Handler interface {
45 ServeHTTP(ResponseWriter, *Request)
48 // A ResponseWriter interface is used by an HTTP handler to
49 // construct an HTTP response.
50 type ResponseWriter interface {
51 // Header returns the header map that will be sent by WriteHeader.
52 // Changing the header after a call to WriteHeader (or Write) has
53 // no effect.
54 Header() Header
56 // Write writes the data to the connection as part of an HTTP reply.
57 // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
58 // before writing the data. If the Header does not contain a
59 // Content-Type line, Write adds a Content-Type set to the result of passing
60 // the initial 512 bytes of written data to DetectContentType.
61 Write([]byte) (int, error)
63 // WriteHeader sends an HTTP response header with status code.
64 // If WriteHeader is not called explicitly, the first call to Write
65 // will trigger an implicit WriteHeader(http.StatusOK).
66 // Thus explicit calls to WriteHeader are mainly used to
67 // send error codes.
68 WriteHeader(int)
71 // The Flusher interface is implemented by ResponseWriters that allow
72 // an HTTP handler to flush buffered data to the client.
74 // Note that even for ResponseWriters that support Flush,
75 // if the client is connected through an HTTP proxy,
76 // the buffered data may not reach the client until the response
77 // completes.
78 type Flusher interface {
79 // Flush sends any buffered data to the client.
80 Flush()
83 // The Hijacker interface is implemented by ResponseWriters that allow
84 // an HTTP handler to take over the connection.
85 type Hijacker interface {
86 // Hijack lets the caller take over the connection.
87 // After a call to Hijack(), the HTTP server library
88 // will not do anything else with the connection.
89 // It becomes the caller's responsibility to manage
90 // and close the connection.
91 Hijack() (net.Conn, *bufio.ReadWriter, error)
94 // The CloseNotifier interface is implemented by ResponseWriters which
95 // allow detecting when the underlying connection has gone away.
97 // This mechanism can be used to cancel long operations on the server
98 // if the client has disconnected before the response is ready.
99 type CloseNotifier interface {
100 // CloseNotify returns a channel that receives a single value
101 // when the client connection has gone away.
102 CloseNotify() <-chan bool
105 // A conn represents the server side of an HTTP connection.
106 type conn struct {
107 remoteAddr string // network address of remote side
108 server *Server // the Server on which the connection arrived
109 rwc net.Conn // i/o connection
110 sr liveSwitchReader // where the LimitReader reads from; usually the rwc
111 lr *io.LimitedReader // io.LimitReader(sr)
112 buf *bufio.ReadWriter // buffered(lr,rwc), reading from bufio->limitReader->sr->rwc
113 tlsState *tls.ConnectionState // or nil when not using TLS
115 mu sync.Mutex // guards the following
116 clientGone bool // if client has disconnected mid-request
117 closeNotifyc chan bool // made lazily
118 hijackedv bool // connection has been hijacked by handler
121 func (c *conn) hijacked() bool {
122 c.mu.Lock()
123 defer c.mu.Unlock()
124 return c.hijackedv
127 func (c *conn) hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
128 c.mu.Lock()
129 defer c.mu.Unlock()
130 if c.hijackedv {
131 return nil, nil, ErrHijacked
133 if c.closeNotifyc != nil {
134 return nil, nil, errors.New("http: Hijack is incompatible with use of CloseNotifier")
136 c.hijackedv = true
137 rwc = c.rwc
138 buf = c.buf
139 c.rwc = nil
140 c.buf = nil
141 return
144 func (c *conn) closeNotify() <-chan bool {
145 c.mu.Lock()
146 defer c.mu.Unlock()
147 if c.closeNotifyc == nil {
148 c.closeNotifyc = make(chan bool, 1)
149 if c.hijackedv {
150 // to obey the function signature, even though
151 // it'll never receive a value.
152 return c.closeNotifyc
154 pr, pw := io.Pipe()
156 readSource := c.sr.r
157 c.sr.Lock()
158 c.sr.r = pr
159 c.sr.Unlock()
160 go func() {
161 _, err := io.Copy(pw, readSource)
162 if err == nil {
163 err = io.EOF
165 pw.CloseWithError(err)
166 c.noteClientGone()
169 return c.closeNotifyc
172 func (c *conn) noteClientGone() {
173 c.mu.Lock()
174 defer c.mu.Unlock()
175 if c.closeNotifyc != nil && !c.clientGone {
176 c.closeNotifyc <- true
178 c.clientGone = true
181 // A switchReader can have its Reader changed at runtime.
182 // It's not safe for concurrent Reads and switches.
183 type switchReader struct {
184 io.Reader
187 // A switchWriter can have its Writer changed at runtime.
188 // It's not safe for concurrent Writes and switches.
189 type switchWriter struct {
190 io.Writer
193 // A liveSwitchReader is a switchReader that's safe for concurrent
194 // reads and switches, if its mutex is held.
195 type liveSwitchReader struct {
196 sync.Mutex
197 r io.Reader
200 func (sr *liveSwitchReader) Read(p []byte) (n int, err error) {
201 sr.Lock()
202 r := sr.r
203 sr.Unlock()
204 return r.Read(p)
207 // This should be >= 512 bytes for DetectContentType,
208 // but otherwise it's somewhat arbitrary.
209 const bufferBeforeChunkingSize = 2048
211 // chunkWriter writes to a response's conn buffer, and is the writer
212 // wrapped by the response.bufw buffered writer.
214 // chunkWriter also is responsible for finalizing the Header, including
215 // conditionally setting the Content-Type and setting a Content-Length
216 // in cases where the handler's final output is smaller than the buffer
217 // size. It also conditionally adds chunk headers, when in chunking mode.
219 // See the comment above (*response).Write for the entire write flow.
220 type chunkWriter struct {
221 res *response
223 // header is either nil or a deep clone of res.handlerHeader
224 // at the time of res.WriteHeader, if res.WriteHeader is
225 // called and extra buffering is being done to calculate
226 // Content-Type and/or Content-Length.
227 header Header
229 // wroteHeader tells whether the header's been written to "the
230 // wire" (or rather: w.conn.buf). this is unlike
231 // (*response).wroteHeader, which tells only whether it was
232 // logically written.
233 wroteHeader bool
235 // set by the writeHeader method:
236 chunking bool // using chunked transfer encoding for reply body
239 var (
240 crlf = []byte("\r\n")
241 colonSpace = []byte(": ")
244 func (cw *chunkWriter) Write(p []byte) (n int, err error) {
245 if !cw.wroteHeader {
246 cw.writeHeader(p)
248 if cw.res.req.Method == "HEAD" {
249 // Eat writes.
250 return len(p), nil
252 if cw.chunking {
253 _, err = fmt.Fprintf(cw.res.conn.buf, "%x\r\n", len(p))
254 if err != nil {
255 cw.res.conn.rwc.Close()
256 return
259 n, err = cw.res.conn.buf.Write(p)
260 if cw.chunking && err == nil {
261 _, err = cw.res.conn.buf.Write(crlf)
263 if err != nil {
264 cw.res.conn.rwc.Close()
266 return
269 func (cw *chunkWriter) flush() {
270 if !cw.wroteHeader {
271 cw.writeHeader(nil)
273 cw.res.conn.buf.Flush()
276 func (cw *chunkWriter) close() {
277 if !cw.wroteHeader {
278 cw.writeHeader(nil)
280 if cw.chunking {
281 // zero EOF chunk, trailer key/value pairs (currently
282 // unsupported in Go's server), followed by a blank
283 // line.
284 cw.res.conn.buf.WriteString("0\r\n\r\n")
288 // A response represents the server side of an HTTP response.
289 type response struct {
290 conn *conn
291 req *Request // request for this response
292 wroteHeader bool // reply header has been (logically) written
293 wroteContinue bool // 100 Continue response was written
295 w *bufio.Writer // buffers output in chunks to chunkWriter
296 cw chunkWriter
297 sw *switchWriter // of the bufio.Writer, for return to putBufioWriter
299 // handlerHeader is the Header that Handlers get access to,
300 // which may be retained and mutated even after WriteHeader.
301 // handlerHeader is copied into cw.header at WriteHeader
302 // time, and privately mutated thereafter.
303 handlerHeader Header
304 calledHeader bool // handler accessed handlerHeader via Header
306 written int64 // number of bytes written in body
307 contentLength int64 // explicitly-declared Content-Length; or -1
308 status int // status code passed to WriteHeader
310 // close connection after this reply. set on request and
311 // updated after response from handler if there's a
312 // "Connection: keep-alive" response header and a
313 // Content-Length.
314 closeAfterReply bool
316 // requestBodyLimitHit is set by requestTooLarge when
317 // maxBytesReader hits its max size. It is checked in
318 // WriteHeader, to make sure we don't consume the
319 // remaining request body to try to advance to the next HTTP
320 // request. Instead, when this is set, we stop reading
321 // subsequent requests on this connection and stop reading
322 // input from it.
323 requestBodyLimitHit bool
325 handlerDone bool // set true when the handler exits
327 // Buffers for Date and Content-Length
328 dateBuf [len(TimeFormat)]byte
329 clenBuf [10]byte
332 // requestTooLarge is called by maxBytesReader when too much input has
333 // been read from the client.
334 func (w *response) requestTooLarge() {
335 w.closeAfterReply = true
336 w.requestBodyLimitHit = true
337 if !w.wroteHeader {
338 w.Header().Set("Connection", "close")
342 // needsSniff reports whether a Content-Type still needs to be sniffed.
343 func (w *response) needsSniff() bool {
344 _, haveType := w.handlerHeader["Content-Type"]
345 return !w.cw.wroteHeader && !haveType && w.written < sniffLen
348 // writerOnly hides an io.Writer value's optional ReadFrom method
349 // from io.Copy.
350 type writerOnly struct {
351 io.Writer
354 func srcIsRegularFile(src io.Reader) (isRegular bool, err error) {
355 switch v := src.(type) {
356 case *os.File:
357 fi, err := v.Stat()
358 if err != nil {
359 return false, err
361 return fi.Mode().IsRegular(), nil
362 case *io.LimitedReader:
363 return srcIsRegularFile(v.R)
364 default:
365 return
369 // ReadFrom is here to optimize copying from an *os.File regular file
370 // to a *net.TCPConn with sendfile.
371 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
372 // Our underlying w.conn.rwc is usually a *TCPConn (with its
373 // own ReadFrom method). If not, or if our src isn't a regular
374 // file, just fall back to the normal copy method.
375 rf, ok := w.conn.rwc.(io.ReaderFrom)
376 regFile, err := srcIsRegularFile(src)
377 if err != nil {
378 return 0, err
380 if !ok || !regFile {
381 return io.Copy(writerOnly{w}, src)
384 // sendfile path:
386 if !w.wroteHeader {
387 w.WriteHeader(StatusOK)
390 if w.needsSniff() {
391 n0, err := io.Copy(writerOnly{w}, io.LimitReader(src, sniffLen))
392 n += n0
393 if err != nil {
394 return n, err
398 w.w.Flush() // get rid of any previous writes
399 w.cw.flush() // make sure Header is written; flush data to rwc
401 // Now that cw has been flushed, its chunking field is guaranteed initialized.
402 if !w.cw.chunking && w.bodyAllowed() {
403 n0, err := rf.ReadFrom(src)
404 n += n0
405 w.written += n0
406 return n, err
409 n0, err := io.Copy(writerOnly{w}, src)
410 n += n0
411 return n, err
414 // noLimit is an effective infinite upper bound for io.LimitedReader
415 const noLimit int64 = (1 << 63) - 1
417 // debugServerConnections controls whether all server connections are wrapped
418 // with a verbose logging wrapper.
419 const debugServerConnections = false
421 // Create new connection from rwc.
422 func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
423 c = new(conn)
424 c.remoteAddr = rwc.RemoteAddr().String()
425 c.server = srv
426 c.rwc = rwc
427 if debugServerConnections {
428 c.rwc = newLoggingConn("server", c.rwc)
430 c.sr = liveSwitchReader{r: c.rwc}
431 c.lr = io.LimitReader(&c.sr, noLimit).(*io.LimitedReader)
432 br := newBufioReader(c.lr)
433 bw := newBufioWriterSize(c.rwc, 4<<10)
434 c.buf = bufio.NewReadWriter(br, bw)
435 return c, nil
438 var (
439 bufioReaderPool sync.Pool
440 bufioWriter2kPool sync.Pool
441 bufioWriter4kPool sync.Pool
444 func bufioWriterPool(size int) *sync.Pool {
445 switch size {
446 case 2 << 10:
447 return &bufioWriter2kPool
448 case 4 << 10:
449 return &bufioWriter4kPool
451 return nil
454 func newBufioReader(r io.Reader) *bufio.Reader {
455 if v := bufioReaderPool.Get(); v != nil {
456 br := v.(*bufio.Reader)
457 br.Reset(r)
458 return br
460 return bufio.NewReader(r)
463 func putBufioReader(br *bufio.Reader) {
464 br.Reset(nil)
465 bufioReaderPool.Put(br)
468 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
469 pool := bufioWriterPool(size)
470 if pool != nil {
471 if v := pool.Get(); v != nil {
472 bw := v.(*bufio.Writer)
473 bw.Reset(w)
474 return bw
477 return bufio.NewWriterSize(w, size)
480 func putBufioWriter(bw *bufio.Writer) {
481 bw.Reset(nil)
482 if pool := bufioWriterPool(bw.Available()); pool != nil {
483 pool.Put(bw)
487 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
488 // in an HTTP request.
489 // This can be overridden by setting Server.MaxHeaderBytes.
490 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
492 func (srv *Server) maxHeaderBytes() int {
493 if srv.MaxHeaderBytes > 0 {
494 return srv.MaxHeaderBytes
496 return DefaultMaxHeaderBytes
499 // wrapper around io.ReaderCloser which on first read, sends an
500 // HTTP/1.1 100 Continue header
501 type expectContinueReader struct {
502 resp *response
503 readCloser io.ReadCloser
504 closed bool
507 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
508 if ecr.closed {
509 return 0, ErrBodyReadAfterClose
511 if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked() {
512 ecr.resp.wroteContinue = true
513 ecr.resp.conn.buf.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
514 ecr.resp.conn.buf.Flush()
516 return ecr.readCloser.Read(p)
519 func (ecr *expectContinueReader) Close() error {
520 ecr.closed = true
521 return ecr.readCloser.Close()
524 // TimeFormat is the time format to use with
525 // time.Parse and time.Time.Format when parsing
526 // or generating times in HTTP headers.
527 // It is like time.RFC1123 but hard codes GMT as the time zone.
528 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
530 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
531 func appendTime(b []byte, t time.Time) []byte {
532 const days = "SunMonTueWedThuFriSat"
533 const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
535 t = t.UTC()
536 yy, mm, dd := t.Date()
537 hh, mn, ss := t.Clock()
538 day := days[3*t.Weekday():]
539 mon := months[3*(mm-1):]
541 return append(b,
542 day[0], day[1], day[2], ',', ' ',
543 byte('0'+dd/10), byte('0'+dd%10), ' ',
544 mon[0], mon[1], mon[2], ' ',
545 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
546 byte('0'+hh/10), byte('0'+hh%10), ':',
547 byte('0'+mn/10), byte('0'+mn%10), ':',
548 byte('0'+ss/10), byte('0'+ss%10), ' ',
549 'G', 'M', 'T')
552 var errTooLarge = errors.New("http: request too large")
554 // Read next request from connection.
555 func (c *conn) readRequest() (w *response, err error) {
556 if c.hijacked() {
557 return nil, ErrHijacked
560 if d := c.server.ReadTimeout; d != 0 {
561 c.rwc.SetReadDeadline(time.Now().Add(d))
563 if d := c.server.WriteTimeout; d != 0 {
564 defer func() {
565 c.rwc.SetWriteDeadline(time.Now().Add(d))
569 c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
570 var req *Request
571 if req, err = ReadRequest(c.buf.Reader); err != nil {
572 if c.lr.N == 0 {
573 return nil, errTooLarge
575 return nil, err
577 c.lr.N = noLimit
579 req.RemoteAddr = c.remoteAddr
580 req.TLS = c.tlsState
582 w = &response{
583 conn: c,
584 req: req,
585 handlerHeader: make(Header),
586 contentLength: -1,
588 w.cw.res = w
589 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
590 return w, nil
593 func (w *response) Header() Header {
594 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
595 // Accessing the header between logically writing it
596 // and physically writing it means we need to allocate
597 // a clone to snapshot the logically written state.
598 w.cw.header = w.handlerHeader.clone()
600 w.calledHeader = true
601 return w.handlerHeader
604 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
605 // consumed by a handler that the server will read from the client
606 // in order to keep a connection alive. If there are more bytes than
607 // this then the server to be paranoid instead sends a "Connection:
608 // close" response.
610 // This number is approximately what a typical machine's TCP buffer
611 // size is anyway. (if we have the bytes on the machine, we might as
612 // well read them)
613 const maxPostHandlerReadBytes = 256 << 10
615 func (w *response) WriteHeader(code int) {
616 if w.conn.hijacked() {
617 log.Print("http: response.WriteHeader on hijacked connection")
618 return
620 if w.wroteHeader {
621 log.Print("http: multiple response.WriteHeader calls")
622 return
624 w.wroteHeader = true
625 w.status = code
627 if w.calledHeader && w.cw.header == nil {
628 w.cw.header = w.handlerHeader.clone()
631 if cl := w.handlerHeader.get("Content-Length"); cl != "" {
632 v, err := strconv.ParseInt(cl, 10, 64)
633 if err == nil && v >= 0 {
634 w.contentLength = v
635 } else {
636 log.Printf("http: invalid Content-Length of %q", cl)
637 w.handlerHeader.Del("Content-Length")
642 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
643 // This type is used to avoid extra allocations from cloning and/or populating
644 // the response Header map and all its 1-element slices.
645 type extraHeader struct {
646 contentType string
647 connection string
648 transferEncoding string
649 date []byte // written if not nil
650 contentLength []byte // written if not nil
653 // Sorted the same as extraHeader.Write's loop.
654 var extraHeaderKeys = [][]byte{
655 []byte("Content-Type"),
656 []byte("Connection"),
657 []byte("Transfer-Encoding"),
660 var (
661 headerContentLength = []byte("Content-Length: ")
662 headerDate = []byte("Date: ")
665 // Write writes the headers described in h to w.
667 // This method has a value receiver, despite the somewhat large size
668 // of h, because it prevents an allocation. The escape analysis isn't
669 // smart enough to realize this function doesn't mutate h.
670 func (h extraHeader) Write(w *bufio.Writer) {
671 if h.date != nil {
672 w.Write(headerDate)
673 w.Write(h.date)
674 w.Write(crlf)
676 if h.contentLength != nil {
677 w.Write(headerContentLength)
678 w.Write(h.contentLength)
679 w.Write(crlf)
681 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
682 if v != "" {
683 w.Write(extraHeaderKeys[i])
684 w.Write(colonSpace)
685 w.WriteString(v)
686 w.Write(crlf)
691 // writeHeader finalizes the header sent to the client and writes it
692 // to cw.res.conn.buf.
694 // p is not written by writeHeader, but is the first chunk of the body
695 // that will be written. It is sniffed for a Content-Type if none is
696 // set explicitly. It's also used to set the Content-Length, if the
697 // total body size was small and the handler has already finished
698 // running.
699 func (cw *chunkWriter) writeHeader(p []byte) {
700 if cw.wroteHeader {
701 return
703 cw.wroteHeader = true
705 w := cw.res
706 isHEAD := w.req.Method == "HEAD"
708 // header is written out to w.conn.buf below. Depending on the
709 // state of the handler, we either own the map or not. If we
710 // don't own it, the exclude map is created lazily for
711 // WriteSubset to remove headers. The setHeader struct holds
712 // headers we need to add.
713 header := cw.header
714 owned := header != nil
715 if !owned {
716 header = w.handlerHeader
718 var excludeHeader map[string]bool
719 delHeader := func(key string) {
720 if owned {
721 header.Del(key)
722 return
724 if _, ok := header[key]; !ok {
725 return
727 if excludeHeader == nil {
728 excludeHeader = make(map[string]bool)
730 excludeHeader[key] = true
732 var setHeader extraHeader
734 // If the handler is done but never sent a Content-Length
735 // response header and this is our first (and last) write, set
736 // it, even to zero. This helps HTTP/1.0 clients keep their
737 // "keep-alive" connections alive.
738 // Exceptions: 304 responses never get Content-Length, and if
739 // it was a HEAD request, we don't know the difference between
740 // 0 actual bytes and 0 bytes because the handler noticed it
741 // was a HEAD request and chose not to write anything. So for
742 // HEAD, the handler should either write the Content-Length or
743 // write non-zero bytes. If it's actually 0 bytes and the
744 // handler never looked at the Request.Method, we just don't
745 // send a Content-Length header.
746 if w.handlerDone && w.status != StatusNotModified && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
747 w.contentLength = int64(len(p))
748 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
751 // If this was an HTTP/1.0 request with keep-alive and we sent a
752 // Content-Length back, we can make this a keep-alive response ...
753 if w.req.wantsHttp10KeepAlive() {
754 sentLength := header.get("Content-Length") != ""
755 if sentLength && header.get("Connection") == "keep-alive" {
756 w.closeAfterReply = false
760 // Check for a explicit (and valid) Content-Length header.
761 hasCL := w.contentLength != -1
763 if w.req.wantsHttp10KeepAlive() && (isHEAD || hasCL) {
764 _, connectionHeaderSet := header["Connection"]
765 if !connectionHeaderSet {
766 setHeader.connection = "keep-alive"
768 } else if !w.req.ProtoAtLeast(1, 1) || w.req.wantsClose() {
769 w.closeAfterReply = true
772 if header.get("Connection") == "close" {
773 w.closeAfterReply = true
776 // Per RFC 2616, we should consume the request body before
777 // replying, if the handler hasn't already done so. But we
778 // don't want to do an unbounded amount of reading here for
779 // DoS reasons, so we only try up to a threshold.
780 if w.req.ContentLength != 0 && !w.closeAfterReply {
781 ecr, isExpecter := w.req.Body.(*expectContinueReader)
782 if !isExpecter || ecr.resp.wroteContinue {
783 n, _ := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1)
784 if n >= maxPostHandlerReadBytes {
785 w.requestTooLarge()
786 delHeader("Connection")
787 setHeader.connection = "close"
788 } else {
789 w.req.Body.Close()
794 code := w.status
795 if code == StatusNotModified {
796 // Must not have body.
797 // RFC 2616 section 10.3.5: "the response MUST NOT include other entity-headers"
798 for _, k := range []string{"Content-Type", "Content-Length", "Transfer-Encoding"} {
799 delHeader(k)
801 } else {
802 // If no content type, apply sniffing algorithm to body.
803 _, haveType := header["Content-Type"]
804 if !haveType {
805 setHeader.contentType = DetectContentType(p)
809 if _, ok := header["Date"]; !ok {
810 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
813 te := header.get("Transfer-Encoding")
814 hasTE := te != ""
815 if hasCL && hasTE && te != "identity" {
816 // TODO: return an error if WriteHeader gets a return parameter
817 // For now just ignore the Content-Length.
818 log.Printf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
819 te, w.contentLength)
820 delHeader("Content-Length")
821 hasCL = false
824 if w.req.Method == "HEAD" || code == StatusNotModified {
825 // do nothing
826 } else if code == StatusNoContent {
827 delHeader("Transfer-Encoding")
828 } else if hasCL {
829 delHeader("Transfer-Encoding")
830 } else if w.req.ProtoAtLeast(1, 1) {
831 // HTTP/1.1 or greater: use chunked transfer encoding
832 // to avoid closing the connection at EOF.
833 // TODO: this blows away any custom or stacked Transfer-Encoding they
834 // might have set. Deal with that as need arises once we have a valid
835 // use case.
836 cw.chunking = true
837 setHeader.transferEncoding = "chunked"
838 } else {
839 // HTTP version < 1.1: cannot do chunked transfer
840 // encoding and we don't know the Content-Length so
841 // signal EOF by closing connection.
842 w.closeAfterReply = true
843 delHeader("Transfer-Encoding") // in case already set
846 // Cannot use Content-Length with non-identity Transfer-Encoding.
847 if cw.chunking {
848 delHeader("Content-Length")
850 if !w.req.ProtoAtLeast(1, 0) {
851 return
854 if w.closeAfterReply && !hasToken(cw.header.get("Connection"), "close") {
855 delHeader("Connection")
856 if w.req.ProtoAtLeast(1, 1) {
857 setHeader.connection = "close"
861 w.conn.buf.WriteString(statusLine(w.req, code))
862 cw.header.WriteSubset(w.conn.buf, excludeHeader)
863 setHeader.Write(w.conn.buf.Writer)
864 w.conn.buf.Write(crlf)
867 // statusLines is a cache of Status-Line strings, keyed by code (for
868 // HTTP/1.1) or negative code (for HTTP/1.0). This is faster than a
869 // map keyed by struct of two fields. This map's max size is bounded
870 // by 2*len(statusText), two protocol types for each known official
871 // status code in the statusText map.
872 var (
873 statusMu sync.RWMutex
874 statusLines = make(map[int]string)
877 // statusLine returns a response Status-Line (RFC 2616 Section 6.1)
878 // for the given request and response status code.
879 func statusLine(req *Request, code int) string {
880 // Fast path:
881 key := code
882 proto11 := req.ProtoAtLeast(1, 1)
883 if !proto11 {
884 key = -key
886 statusMu.RLock()
887 line, ok := statusLines[key]
888 statusMu.RUnlock()
889 if ok {
890 return line
893 // Slow path:
894 proto := "HTTP/1.0"
895 if proto11 {
896 proto = "HTTP/1.1"
898 codestring := strconv.Itoa(code)
899 text, ok := statusText[code]
900 if !ok {
901 text = "status code " + codestring
903 line = proto + " " + codestring + " " + text + "\r\n"
904 if ok {
905 statusMu.Lock()
906 defer statusMu.Unlock()
907 statusLines[key] = line
909 return line
912 // bodyAllowed returns true if a Write is allowed for this response type.
913 // It's illegal to call this before the header has been flushed.
914 func (w *response) bodyAllowed() bool {
915 if !w.wroteHeader {
916 panic("")
918 return w.status != StatusNotModified
921 // The Life Of A Write is like this:
923 // Handler starts. No header has been sent. The handler can either
924 // write a header, or just start writing. Writing before sending a header
925 // sends an implicitly empty 200 OK header.
927 // If the handler didn't declare a Content-Length up front, we either
928 // go into chunking mode or, if the handler finishes running before
929 // the chunking buffer size, we compute a Content-Length and send that
930 // in the header instead.
932 // Likewise, if the handler didn't set a Content-Type, we sniff that
933 // from the initial chunk of output.
935 // The Writers are wired together like:
937 // 1. *response (the ResponseWriter) ->
938 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
939 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
940 // and which writes the chunk headers, if needed.
941 // 4. conn.buf, a bufio.Writer of default (4kB) bytes
942 // 5. the rwc, the net.Conn.
944 // TODO(bradfitz): short-circuit some of the buffering when the
945 // initial header contains both a Content-Type and Content-Length.
946 // Also short-circuit in (1) when the header's been sent and not in
947 // chunking mode, writing directly to (4) instead, if (2) has no
948 // buffered data. More generally, we could short-circuit from (1) to
949 // (3) even in chunking mode if the write size from (1) is over some
950 // threshold and nothing is in (2). The answer might be mostly making
951 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
952 // with this instead.
953 func (w *response) Write(data []byte) (n int, err error) {
954 return w.write(len(data), data, "")
957 func (w *response) WriteString(data string) (n int, err error) {
958 return w.write(len(data), nil, data)
961 // either dataB or dataS is non-zero.
962 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
963 if w.conn.hijacked() {
964 log.Print("http: response.Write on hijacked connection")
965 return 0, ErrHijacked
967 if !w.wroteHeader {
968 w.WriteHeader(StatusOK)
970 if lenData == 0 {
971 return 0, nil
973 if !w.bodyAllowed() {
974 return 0, ErrBodyNotAllowed
977 w.written += int64(lenData) // ignoring errors, for errorKludge
978 if w.contentLength != -1 && w.written > w.contentLength {
979 return 0, ErrContentLength
981 if dataB != nil {
982 return w.w.Write(dataB)
983 } else {
984 return w.w.WriteString(dataS)
988 func (w *response) finishRequest() {
989 w.handlerDone = true
991 if !w.wroteHeader {
992 w.WriteHeader(StatusOK)
995 w.w.Flush()
996 putBufioWriter(w.w)
997 w.cw.close()
998 w.conn.buf.Flush()
1000 // Close the body, unless we're about to close the whole TCP connection
1001 // anyway.
1002 if !w.closeAfterReply {
1003 w.req.Body.Close()
1005 if w.req.MultipartForm != nil {
1006 w.req.MultipartForm.RemoveAll()
1009 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
1010 // Did not write enough. Avoid getting out of sync.
1011 w.closeAfterReply = true
1015 func (w *response) Flush() {
1016 if !w.wroteHeader {
1017 w.WriteHeader(StatusOK)
1019 w.w.Flush()
1020 w.cw.flush()
1023 func (c *conn) finalFlush() {
1024 if c.buf != nil {
1025 c.buf.Flush()
1027 // Steal the bufio.Reader (~4KB worth of memory) and its associated
1028 // reader for a future connection.
1029 putBufioReader(c.buf.Reader)
1031 // Steal the bufio.Writer (~4KB worth of memory) and its associated
1032 // writer for a future connection.
1033 putBufioWriter(c.buf.Writer)
1035 c.buf = nil
1039 // Close the connection.
1040 func (c *conn) close() {
1041 c.finalFlush()
1042 if c.rwc != nil {
1043 c.rwc.Close()
1044 c.rwc = nil
1048 // rstAvoidanceDelay is the amount of time we sleep after closing the
1049 // write side of a TCP connection before closing the entire socket.
1050 // By sleeping, we increase the chances that the client sees our FIN
1051 // and processes its final data before they process the subsequent RST
1052 // from closing a connection with known unread data.
1053 // This RST seems to occur mostly on BSD systems. (And Windows?)
1054 // This timeout is somewhat arbitrary (~latency around the planet).
1055 const rstAvoidanceDelay = 500 * time.Millisecond
1057 // closeWrite flushes any outstanding data and sends a FIN packet (if
1058 // client is connected via TCP), signalling that we're done. We then
1059 // pause for a bit, hoping the client processes it before `any
1060 // subsequent RST.
1062 // See http://golang.org/issue/3595
1063 func (c *conn) closeWriteAndWait() {
1064 c.finalFlush()
1065 if tcp, ok := c.rwc.(*net.TCPConn); ok {
1066 tcp.CloseWrite()
1068 time.Sleep(rstAvoidanceDelay)
1071 // validNPN reports whether the proto is not a blacklisted Next
1072 // Protocol Negotiation protocol. Empty and built-in protocol types
1073 // are blacklisted and can't be overridden with alternate
1074 // implementations.
1075 func validNPN(proto string) bool {
1076 switch proto {
1077 case "", "http/1.1", "http/1.0":
1078 return false
1080 return true
1083 // Serve a new connection.
1084 func (c *conn) serve() {
1085 defer func() {
1086 if err := recover(); err != nil {
1087 const size = 4096
1088 buf := make([]byte, size)
1089 buf = buf[:runtime.Stack(buf, false)]
1090 log.Printf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
1092 if !c.hijacked() {
1093 c.close()
1097 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
1098 if d := c.server.ReadTimeout; d != 0 {
1099 c.rwc.SetReadDeadline(time.Now().Add(d))
1101 if d := c.server.WriteTimeout; d != 0 {
1102 c.rwc.SetWriteDeadline(time.Now().Add(d))
1104 if err := tlsConn.Handshake(); err != nil {
1105 return
1107 c.tlsState = new(tls.ConnectionState)
1108 *c.tlsState = tlsConn.ConnectionState()
1109 if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
1110 if fn := c.server.TLSNextProto[proto]; fn != nil {
1111 h := initNPNRequest{tlsConn, serverHandler{c.server}}
1112 fn(c.server, tlsConn, h)
1114 return
1118 for {
1119 w, err := c.readRequest()
1120 if err != nil {
1121 if err == errTooLarge {
1122 // Their HTTP client may or may not be
1123 // able to read this if we're
1124 // responding to them and hanging up
1125 // while they're still writing their
1126 // request. Undefined behavior.
1127 io.WriteString(c.rwc, "HTTP/1.1 413 Request Entity Too Large\r\n\r\n")
1128 c.closeWriteAndWait()
1129 break
1130 } else if err == io.EOF {
1131 break // Don't reply
1132 } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
1133 break // Don't reply
1135 io.WriteString(c.rwc, "HTTP/1.1 400 Bad Request\r\n\r\n")
1136 break
1139 // Expect 100 Continue support
1140 req := w.req
1141 if req.expectsContinue() {
1142 if req.ProtoAtLeast(1, 1) {
1143 // Wrap the Body reader with one that replies on the connection
1144 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
1146 if req.ContentLength == 0 {
1147 w.Header().Set("Connection", "close")
1148 w.WriteHeader(StatusBadRequest)
1149 w.finishRequest()
1150 break
1152 req.Header.Del("Expect")
1153 } else if req.Header.get("Expect") != "" {
1154 w.sendExpectationFailed()
1155 break
1158 // HTTP cannot have multiple simultaneous active requests.[*]
1159 // Until the server replies to this request, it can't read another,
1160 // so we might as well run the handler in this goroutine.
1161 // [*] Not strictly true: HTTP pipelining. We could let them all process
1162 // in parallel even if their responses need to be serialized.
1163 serverHandler{c.server}.ServeHTTP(w, w.req)
1164 if c.hijacked() {
1165 return
1167 w.finishRequest()
1168 if w.closeAfterReply {
1169 if w.requestBodyLimitHit {
1170 c.closeWriteAndWait()
1172 break
1177 func (w *response) sendExpectationFailed() {
1178 // TODO(bradfitz): let ServeHTTP handlers handle
1179 // requests with non-standard expectation[s]? Seems
1180 // theoretical at best, and doesn't fit into the
1181 // current ServeHTTP model anyway. We'd need to
1182 // make the ResponseWriter an optional
1183 // "ExpectReplier" interface or something.
1185 // For now we'll just obey RFC 2616 14.20 which says
1186 // "If a server receives a request containing an
1187 // Expect field that includes an expectation-
1188 // extension that it does not support, it MUST
1189 // respond with a 417 (Expectation Failed) status."
1190 w.Header().Set("Connection", "close")
1191 w.WriteHeader(StatusExpectationFailed)
1192 w.finishRequest()
1195 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
1196 // and a Hijacker.
1197 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
1198 if w.wroteHeader {
1199 w.cw.flush()
1201 // Release the bufioWriter that writes to the chunk writer, it is not
1202 // used after a connection has been hijacked.
1203 rwc, buf, err = w.conn.hijack()
1204 if err == nil {
1205 putBufioWriter(w.w)
1206 w.w = nil
1208 return rwc, buf, err
1211 func (w *response) CloseNotify() <-chan bool {
1212 return w.conn.closeNotify()
1215 // The HandlerFunc type is an adapter to allow the use of
1216 // ordinary functions as HTTP handlers. If f is a function
1217 // with the appropriate signature, HandlerFunc(f) is a
1218 // Handler object that calls f.
1219 type HandlerFunc func(ResponseWriter, *Request)
1221 // ServeHTTP calls f(w, r).
1222 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
1223 f(w, r)
1226 // Helper handlers
1228 // Error replies to the request with the specified error message and HTTP code.
1229 // The error message should be plain text.
1230 func Error(w ResponseWriter, error string, code int) {
1231 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
1232 w.WriteHeader(code)
1233 fmt.Fprintln(w, error)
1236 // NotFound replies to the request with an HTTP 404 not found error.
1237 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
1239 // NotFoundHandler returns a simple request handler
1240 // that replies to each request with a ``404 page not found'' reply.
1241 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
1243 // StripPrefix returns a handler that serves HTTP requests
1244 // by removing the given prefix from the request URL's Path
1245 // and invoking the handler h. StripPrefix handles a
1246 // request for a path that doesn't begin with prefix by
1247 // replying with an HTTP 404 not found error.
1248 func StripPrefix(prefix string, h Handler) Handler {
1249 if prefix == "" {
1250 return h
1252 return HandlerFunc(func(w ResponseWriter, r *Request) {
1253 if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
1254 r.URL.Path = p
1255 h.ServeHTTP(w, r)
1256 } else {
1257 NotFound(w, r)
1262 // Redirect replies to the request with a redirect to url,
1263 // which may be a path relative to the request path.
1264 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
1265 if u, err := url.Parse(urlStr); err == nil {
1266 // If url was relative, make absolute by
1267 // combining with request path.
1268 // The browser would probably do this for us,
1269 // but doing it ourselves is more reliable.
1271 // NOTE(rsc): RFC 2616 says that the Location
1272 // line must be an absolute URI, like
1273 // "http://www.google.com/redirect/",
1274 // not a path like "/redirect/".
1275 // Unfortunately, we don't know what to
1276 // put in the host name section to get the
1277 // client to connect to us again, so we can't
1278 // know the right absolute URI to send back.
1279 // Because of this problem, no one pays attention
1280 // to the RFC; they all send back just a new path.
1281 // So do we.
1282 oldpath := r.URL.Path
1283 if oldpath == "" { // should not happen, but avoid a crash if it does
1284 oldpath = "/"
1286 if u.Scheme == "" {
1287 // no leading http://server
1288 if urlStr == "" || urlStr[0] != '/' {
1289 // make relative path absolute
1290 olddir, _ := path.Split(oldpath)
1291 urlStr = olddir + urlStr
1294 var query string
1295 if i := strings.Index(urlStr, "?"); i != -1 {
1296 urlStr, query = urlStr[:i], urlStr[i:]
1299 // clean up but preserve trailing slash
1300 trailing := strings.HasSuffix(urlStr, "/")
1301 urlStr = path.Clean(urlStr)
1302 if trailing && !strings.HasSuffix(urlStr, "/") {
1303 urlStr += "/"
1305 urlStr += query
1309 w.Header().Set("Location", urlStr)
1310 w.WriteHeader(code)
1312 // RFC2616 recommends that a short note "SHOULD" be included in the
1313 // response because older user agents may not understand 301/307.
1314 // Shouldn't send the response for POST or HEAD; that leaves GET.
1315 if r.Method == "GET" {
1316 note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
1317 fmt.Fprintln(w, note)
1321 var htmlReplacer = strings.NewReplacer(
1322 "&", "&amp;",
1323 "<", "&lt;",
1324 ">", "&gt;",
1325 // "&#34;" is shorter than "&quot;".
1326 `"`, "&#34;",
1327 // "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
1328 "'", "&#39;",
1331 func htmlEscape(s string) string {
1332 return htmlReplacer.Replace(s)
1335 // Redirect to a fixed URL
1336 type redirectHandler struct {
1337 url string
1338 code int
1341 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
1342 Redirect(w, r, rh.url, rh.code)
1345 // RedirectHandler returns a request handler that redirects
1346 // each request it receives to the given url using the given
1347 // status code.
1348 func RedirectHandler(url string, code int) Handler {
1349 return &redirectHandler{url, code}
1352 // ServeMux is an HTTP request multiplexer.
1353 // It matches the URL of each incoming request against a list of registered
1354 // patterns and calls the handler for the pattern that
1355 // most closely matches the URL.
1357 // Patterns name fixed, rooted paths, like "/favicon.ico",
1358 // or rooted subtrees, like "/images/" (note the trailing slash).
1359 // Longer patterns take precedence over shorter ones, so that
1360 // if there are handlers registered for both "/images/"
1361 // and "/images/thumbnails/", the latter handler will be
1362 // called for paths beginning "/images/thumbnails/" and the
1363 // former will receive requests for any other paths in the
1364 // "/images/" subtree.
1366 // Note that since a pattern ending in a slash names a rooted subtree,
1367 // the pattern "/" matches all paths not matched by other registered
1368 // patterns, not just the URL with Path == "/".
1370 // Patterns may optionally begin with a host name, restricting matches to
1371 // URLs on that host only. Host-specific patterns take precedence over
1372 // general patterns, so that a handler might register for the two patterns
1373 // "/codesearch" and "codesearch.google.com/" without also taking over
1374 // requests for "http://www.google.com/".
1376 // ServeMux also takes care of sanitizing the URL request path,
1377 // redirecting any request containing . or .. elements to an
1378 // equivalent .- and ..-free URL.
1379 type ServeMux struct {
1380 mu sync.RWMutex
1381 m map[string]muxEntry
1382 hosts bool // whether any patterns contain hostnames
1385 type muxEntry struct {
1386 explicit bool
1387 h Handler
1388 pattern string
1391 // NewServeMux allocates and returns a new ServeMux.
1392 func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} }
1394 // DefaultServeMux is the default ServeMux used by Serve.
1395 var DefaultServeMux = NewServeMux()
1397 // Does path match pattern?
1398 func pathMatch(pattern, path string) bool {
1399 if len(pattern) == 0 {
1400 // should not happen
1401 return false
1403 n := len(pattern)
1404 if pattern[n-1] != '/' {
1405 return pattern == path
1407 return len(path) >= n && path[0:n] == pattern
1410 // Return the canonical path for p, eliminating . and .. elements.
1411 func cleanPath(p string) string {
1412 if p == "" {
1413 return "/"
1415 if p[0] != '/' {
1416 p = "/" + p
1418 np := path.Clean(p)
1419 // path.Clean removes trailing slash except for root;
1420 // put the trailing slash back if necessary.
1421 if p[len(p)-1] == '/' && np != "/" {
1422 np += "/"
1424 return np
1427 // Find a handler on a handler map given a path string
1428 // Most-specific (longest) pattern wins
1429 func (mux *ServeMux) match(path string) (h Handler, pattern string) {
1430 var n = 0
1431 for k, v := range mux.m {
1432 if !pathMatch(k, path) {
1433 continue
1435 if h == nil || len(k) > n {
1436 n = len(k)
1437 h = v.h
1438 pattern = v.pattern
1441 return
1444 // Handler returns the handler to use for the given request,
1445 // consulting r.Method, r.Host, and r.URL.Path. It always returns
1446 // a non-nil handler. If the path is not in its canonical form, the
1447 // handler will be an internally-generated handler that redirects
1448 // to the canonical path.
1450 // Handler also returns the registered pattern that matches the
1451 // request or, in the case of internally-generated redirects,
1452 // the pattern that will match after following the redirect.
1454 // If there is no registered handler that applies to the request,
1455 // Handler returns a ``page not found'' handler and an empty pattern.
1456 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
1457 if r.Method != "CONNECT" {
1458 if p := cleanPath(r.URL.Path); p != r.URL.Path {
1459 _, pattern = mux.handler(r.Host, p)
1460 url := *r.URL
1461 url.Path = p
1462 return RedirectHandler(url.String(), StatusMovedPermanently), pattern
1466 return mux.handler(r.Host, r.URL.Path)
1469 // handler is the main implementation of Handler.
1470 // The path is known to be in canonical form, except for CONNECT methods.
1471 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
1472 mux.mu.RLock()
1473 defer mux.mu.RUnlock()
1475 // Host-specific pattern takes precedence over generic ones
1476 if mux.hosts {
1477 h, pattern = mux.match(host + path)
1479 if h == nil {
1480 h, pattern = mux.match(path)
1482 if h == nil {
1483 h, pattern = NotFoundHandler(), ""
1485 return
1488 // ServeHTTP dispatches the request to the handler whose
1489 // pattern most closely matches the request URL.
1490 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
1491 if r.RequestURI == "*" {
1492 if r.ProtoAtLeast(1, 1) {
1493 w.Header().Set("Connection", "close")
1495 w.WriteHeader(StatusBadRequest)
1496 return
1498 h, _ := mux.Handler(r)
1499 h.ServeHTTP(w, r)
1502 // Handle registers the handler for the given pattern.
1503 // If a handler already exists for pattern, Handle panics.
1504 func (mux *ServeMux) Handle(pattern string, handler Handler) {
1505 mux.mu.Lock()
1506 defer mux.mu.Unlock()
1508 if pattern == "" {
1509 panic("http: invalid pattern " + pattern)
1511 if handler == nil {
1512 panic("http: nil handler")
1514 if mux.m[pattern].explicit {
1515 panic("http: multiple registrations for " + pattern)
1518 mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
1520 if pattern[0] != '/' {
1521 mux.hosts = true
1524 // Helpful behavior:
1525 // If pattern is /tree/, insert an implicit permanent redirect for /tree.
1526 // It can be overridden by an explicit registration.
1527 n := len(pattern)
1528 if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
1529 // If pattern contains a host name, strip it and use remaining
1530 // path for redirect.
1531 path := pattern
1532 if pattern[0] != '/' {
1533 // In pattern, at least the last character is a '/', so
1534 // strings.Index can't be -1.
1535 path = pattern[strings.Index(pattern, "/"):]
1537 mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(path, StatusMovedPermanently), pattern: pattern}
1541 // HandleFunc registers the handler function for the given pattern.
1542 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
1543 mux.Handle(pattern, HandlerFunc(handler))
1546 // Handle registers the handler for the given pattern
1547 // in the DefaultServeMux.
1548 // The documentation for ServeMux explains how patterns are matched.
1549 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
1551 // HandleFunc registers the handler function for the given pattern
1552 // in the DefaultServeMux.
1553 // The documentation for ServeMux explains how patterns are matched.
1554 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
1555 DefaultServeMux.HandleFunc(pattern, handler)
1558 // Serve accepts incoming HTTP connections on the listener l,
1559 // creating a new service goroutine for each. The service goroutines
1560 // read requests and then call handler to reply to them.
1561 // Handler is typically nil, in which case the DefaultServeMux is used.
1562 func Serve(l net.Listener, handler Handler) error {
1563 srv := &Server{Handler: handler}
1564 return srv.Serve(l)
1567 // A Server defines parameters for running an HTTP server.
1568 type Server struct {
1569 Addr string // TCP address to listen on, ":http" if empty
1570 Handler Handler // handler to invoke, http.DefaultServeMux if nil
1571 ReadTimeout time.Duration // maximum duration before timing out read of the request
1572 WriteTimeout time.Duration // maximum duration before timing out write of the response
1573 MaxHeaderBytes int // maximum size of request headers, DefaultMaxHeaderBytes if 0
1574 TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
1576 // TLSNextProto optionally specifies a function to take over
1577 // ownership of the provided TLS connection when an NPN
1578 // protocol upgrade has occurred. The map key is the protocol
1579 // name negotiated. The Handler argument should be used to
1580 // handle HTTP requests and will initialize the Request's TLS
1581 // and RemoteAddr if not already set. The connection is
1582 // automatically closed when the function returns.
1583 TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
1586 // serverHandler delegates to either the server's Handler or
1587 // DefaultServeMux and also handles "OPTIONS *" requests.
1588 type serverHandler struct {
1589 srv *Server
1592 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
1593 handler := sh.srv.Handler
1594 if handler == nil {
1595 handler = DefaultServeMux
1597 if req.RequestURI == "*" && req.Method == "OPTIONS" {
1598 handler = globalOptionsHandler{}
1600 handler.ServeHTTP(rw, req)
1603 // ListenAndServe listens on the TCP network address srv.Addr and then
1604 // calls Serve to handle requests on incoming connections. If
1605 // srv.Addr is blank, ":http" is used.
1606 func (srv *Server) ListenAndServe() error {
1607 addr := srv.Addr
1608 if addr == "" {
1609 addr = ":http"
1611 l, e := net.Listen("tcp", addr)
1612 if e != nil {
1613 return e
1615 return srv.Serve(l)
1618 // Serve accepts incoming connections on the Listener l, creating a
1619 // new service goroutine for each. The service goroutines read requests and
1620 // then call srv.Handler to reply to them.
1621 func (srv *Server) Serve(l net.Listener) error {
1622 defer l.Close()
1623 var tempDelay time.Duration // how long to sleep on accept failure
1624 for {
1625 rw, e := l.Accept()
1626 if e != nil {
1627 if ne, ok := e.(net.Error); ok && ne.Temporary() {
1628 if tempDelay == 0 {
1629 tempDelay = 5 * time.Millisecond
1630 } else {
1631 tempDelay *= 2
1633 if max := 1 * time.Second; tempDelay > max {
1634 tempDelay = max
1636 log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay)
1637 time.Sleep(tempDelay)
1638 continue
1640 return e
1642 tempDelay = 0
1643 c, err := srv.newConn(rw)
1644 if err != nil {
1645 continue
1647 go c.serve()
1651 // ListenAndServe listens on the TCP network address addr
1652 // and then calls Serve with handler to handle requests
1653 // on incoming connections. Handler is typically nil,
1654 // in which case the DefaultServeMux is used.
1656 // A trivial example server is:
1658 // package main
1660 // import (
1661 // "io"
1662 // "net/http"
1663 // "log"
1664 // )
1666 // // hello world, the web server
1667 // func HelloServer(w http.ResponseWriter, req *http.Request) {
1668 // io.WriteString(w, "hello, world!\n")
1669 // }
1671 // func main() {
1672 // http.HandleFunc("/hello", HelloServer)
1673 // err := http.ListenAndServe(":12345", nil)
1674 // if err != nil {
1675 // log.Fatal("ListenAndServe: ", err)
1676 // }
1677 // }
1678 func ListenAndServe(addr string, handler Handler) error {
1679 server := &Server{Addr: addr, Handler: handler}
1680 return server.ListenAndServe()
1683 // ListenAndServeTLS acts identically to ListenAndServe, except that it
1684 // expects HTTPS connections. Additionally, files containing a certificate and
1685 // matching private key for the server must be provided. If the certificate
1686 // is signed by a certificate authority, the certFile should be the concatenation
1687 // of the server's certificate followed by the CA's certificate.
1689 // A trivial example server is:
1691 // import (
1692 // "log"
1693 // "net/http"
1694 // )
1696 // func handler(w http.ResponseWriter, req *http.Request) {
1697 // w.Header().Set("Content-Type", "text/plain")
1698 // w.Write([]byte("This is an example server.\n"))
1699 // }
1701 // func main() {
1702 // http.HandleFunc("/", handler)
1703 // log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
1704 // err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
1705 // if err != nil {
1706 // log.Fatal(err)
1707 // }
1708 // }
1710 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
1711 func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
1712 server := &Server{Addr: addr, Handler: handler}
1713 return server.ListenAndServeTLS(certFile, keyFile)
1716 // ListenAndServeTLS listens on the TCP network address srv.Addr and
1717 // then calls Serve to handle requests on incoming TLS connections.
1719 // Filenames containing a certificate and matching private key for
1720 // the server must be provided. If the certificate is signed by a
1721 // certificate authority, the certFile should be the concatenation
1722 // of the server's certificate followed by the CA's certificate.
1724 // If srv.Addr is blank, ":https" is used.
1725 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
1726 addr := srv.Addr
1727 if addr == "" {
1728 addr = ":https"
1730 config := &tls.Config{}
1731 if srv.TLSConfig != nil {
1732 *config = *srv.TLSConfig
1734 if config.NextProtos == nil {
1735 config.NextProtos = []string{"http/1.1"}
1738 var err error
1739 config.Certificates = make([]tls.Certificate, 1)
1740 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
1741 if err != nil {
1742 return err
1745 conn, err := net.Listen("tcp", addr)
1746 if err != nil {
1747 return err
1750 tlsListener := tls.NewListener(conn, config)
1751 return srv.Serve(tlsListener)
1754 // TimeoutHandler returns a Handler that runs h with the given time limit.
1756 // The new Handler calls h.ServeHTTP to handle each request, but if a
1757 // call runs for longer than its time limit, the handler responds with
1758 // a 503 Service Unavailable error and the given message in its body.
1759 // (If msg is empty, a suitable default message will be sent.)
1760 // After such a timeout, writes by h to its ResponseWriter will return
1761 // ErrHandlerTimeout.
1762 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
1763 f := func() <-chan time.Time {
1764 return time.After(dt)
1766 return &timeoutHandler{h, f, msg}
1769 // ErrHandlerTimeout is returned on ResponseWriter Write calls
1770 // in handlers which have timed out.
1771 var ErrHandlerTimeout = errors.New("http: Handler timeout")
1773 type timeoutHandler struct {
1774 handler Handler
1775 timeout func() <-chan time.Time // returns channel producing a timeout
1776 body string
1779 func (h *timeoutHandler) errorBody() string {
1780 if h.body != "" {
1781 return h.body
1783 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
1786 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
1787 done := make(chan bool, 1)
1788 tw := &timeoutWriter{w: w}
1789 go func() {
1790 h.handler.ServeHTTP(tw, r)
1791 done <- true
1793 select {
1794 case <-done:
1795 return
1796 case <-h.timeout():
1797 tw.mu.Lock()
1798 defer tw.mu.Unlock()
1799 if !tw.wroteHeader {
1800 tw.w.WriteHeader(StatusServiceUnavailable)
1801 tw.w.Write([]byte(h.errorBody()))
1803 tw.timedOut = true
1807 type timeoutWriter struct {
1808 w ResponseWriter
1810 mu sync.Mutex
1811 timedOut bool
1812 wroteHeader bool
1815 func (tw *timeoutWriter) Header() Header {
1816 return tw.w.Header()
1819 func (tw *timeoutWriter) Write(p []byte) (int, error) {
1820 tw.mu.Lock()
1821 timedOut := tw.timedOut
1822 tw.mu.Unlock()
1823 if timedOut {
1824 return 0, ErrHandlerTimeout
1826 return tw.w.Write(p)
1829 func (tw *timeoutWriter) WriteHeader(code int) {
1830 tw.mu.Lock()
1831 if tw.timedOut || tw.wroteHeader {
1832 tw.mu.Unlock()
1833 return
1835 tw.wroteHeader = true
1836 tw.mu.Unlock()
1837 tw.w.WriteHeader(code)
1840 // globalOptionsHandler responds to "OPTIONS *" requests.
1841 type globalOptionsHandler struct{}
1843 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
1844 w.Header().Set("Content-Length", "0")
1845 if r.ContentLength != 0 {
1846 // Read up to 4KB of OPTIONS body (as mentioned in the
1847 // spec as being reserved for future use), but anything
1848 // over that is considered a waste of server resources
1849 // (or an attack) and we abort and close the connection,
1850 // courtesy of MaxBytesReader's EOF behavior.
1851 mb := MaxBytesReader(w, r.Body, 4<<10)
1852 io.Copy(ioutil.Discard, mb)
1856 // eofReader is a non-nil io.ReadCloser that always returns EOF.
1857 // It embeds a *strings.Reader so it still has a WriteTo method
1858 // and io.Copy won't need a buffer.
1859 var eofReader = &struct {
1860 *strings.Reader
1861 io.Closer
1863 strings.NewReader(""),
1864 ioutil.NopCloser(nil),
1867 // initNPNRequest is an HTTP handler that initializes certain
1868 // uninitialized fields in its *Request. Such partially-initialized
1869 // Requests come from NPN protocol handlers.
1870 type initNPNRequest struct {
1871 c *tls.Conn
1872 h serverHandler
1875 func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
1876 if req.TLS == nil {
1877 req.TLS = &tls.ConnectionState{}
1878 *req.TLS = h.c.ConnectionState()
1880 if req.Body == nil {
1881 req.Body = eofReader
1883 if req.RemoteAddr == "" {
1884 req.RemoteAddr = h.c.RemoteAddr().String()
1886 h.h.ServeHTTP(rw, req)
1889 // loggingConn is used for debugging.
1890 type loggingConn struct {
1891 name string
1892 net.Conn
1895 var (
1896 uniqNameMu sync.Mutex
1897 uniqNameNext = make(map[string]int)
1900 func newLoggingConn(baseName string, c net.Conn) net.Conn {
1901 uniqNameMu.Lock()
1902 defer uniqNameMu.Unlock()
1903 uniqNameNext[baseName]++
1904 return &loggingConn{
1905 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
1906 Conn: c,
1910 func (c *loggingConn) Write(p []byte) (n int, err error) {
1911 log.Printf("%s.Write(%d) = ....", c.name, len(p))
1912 n, err = c.Conn.Write(p)
1913 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
1914 return
1917 func (c *loggingConn) Read(p []byte) (n int, err error) {
1918 log.Printf("%s.Read(%d) = ....", c.name, len(p))
1919 n, err = c.Conn.Read(p)
1920 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
1921 return
1924 func (c *loggingConn) Close() (err error) {
1925 log.Printf("%s.Close() = ...", c.name)
1926 err = c.Conn.Close()
1927 log.Printf("%s.Close() = %v", c.name, err)
1928 return