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.
31 // Errors introduced by the HTTP server.
33 ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
34 ErrBodyNotAllowed = errors.New("http: response status code does not allow body")
35 ErrHijacked = errors.New("Conn has been hijacked")
36 ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length")
39 // Objects implementing the Handler interface can be
40 // registered to serve a particular path or subtree
41 // in the HTTP server.
43 // ServeHTTP should write reply headers and data to the ResponseWriter
44 // and then return. Returning signals that the request is finished
45 // and that the HTTP server can move on to the next request on
47 type Handler interface {
48 ServeHTTP(ResponseWriter, *Request)
51 // A ResponseWriter interface is used by an HTTP handler to
52 // construct an HTTP response.
53 type ResponseWriter interface {
54 // Header returns the header map that will be sent by WriteHeader.
55 // Changing the header after a call to WriteHeader (or Write) has
59 // Write writes the data to the connection as part of an HTTP reply.
60 // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
61 // before writing the data. If the Header does not contain a
62 // Content-Type line, Write adds a Content-Type set to the result of passing
63 // the initial 512 bytes of written data to DetectContentType.
64 Write([]byte) (int, error)
66 // WriteHeader sends an HTTP response header with status code.
67 // If WriteHeader is not called explicitly, the first call to Write
68 // will trigger an implicit WriteHeader(http.StatusOK).
69 // Thus explicit calls to WriteHeader are mainly used to
74 // The Flusher interface is implemented by ResponseWriters that allow
75 // an HTTP handler to flush buffered data to the client.
77 // Note that even for ResponseWriters that support Flush,
78 // if the client is connected through an HTTP proxy,
79 // the buffered data may not reach the client until the response
81 type Flusher interface {
82 // Flush sends any buffered data to the client.
86 // The Hijacker interface is implemented by ResponseWriters that allow
87 // an HTTP handler to take over the connection.
88 type Hijacker interface {
89 // Hijack lets the caller take over the connection.
90 // After a call to Hijack(), the HTTP server library
91 // will not do anything else with the connection.
92 // It becomes the caller's responsibility to manage
93 // and close the connection.
94 Hijack() (net.Conn, *bufio.ReadWriter, error)
97 // A conn represents the server side of an HTTP connection.
99 remoteAddr string // network address of remote side
100 server *Server // the Server on which the connection arrived
101 rwc net.Conn // i/o connection
102 lr *io.LimitedReader // io.LimitReader(rwc)
103 buf *bufio.ReadWriter // buffered(lr,rwc), reading from bufio->limitReader->rwc
104 hijacked bool // connection has been hijacked by handler
105 tlsState *tls.ConnectionState // or nil when not using TLS
109 // A response represents the server side of an HTTP response.
110 type response struct {
112 req *Request // request for this response
113 chunking bool // using chunked transfer encoding for reply body
114 wroteHeader bool // reply header has been written
115 wroteContinue bool // 100 Continue response was written
116 header Header // reply header parameters
117 written int64 // number of bytes written in body
118 contentLength int64 // explicitly-declared Content-Length; or -1
119 status int // status code passed to WriteHeader
120 needSniff bool // need to sniff to find Content-Type
122 // close connection after this reply. set on request and
123 // updated after response from handler if there's a
124 // "Connection: keep-alive" response header and a
128 // requestBodyLimitHit is set by requestTooLarge when
129 // maxBytesReader hits its max size. It is checked in
130 // WriteHeader, to make sure we don't consume the the
131 // remaining request body to try to advance to the next HTTP
132 // request. Instead, when this is set, we stop doing
133 // subsequent requests on this connection and stop reading
135 requestBodyLimitHit bool
138 // requestTooLarge is called by maxBytesReader when too much input has
139 // been read from the client.
140 func (w *response) requestTooLarge() {
141 w.closeAfterReply = true
142 w.requestBodyLimitHit = true
144 w.Header().Set("Connection", "close")
148 type writerOnly struct {
152 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
153 // Call WriteHeader before checking w.chunking if it hasn't
154 // been called yet, since WriteHeader is what sets w.chunking.
156 w.WriteHeader(StatusOK)
158 if !w.chunking && w.bodyAllowed() && !w.needSniff {
160 if rf, ok := w.conn.rwc.(io.ReaderFrom); ok {
161 n, err = rf.ReadFrom(src)
166 // Fall back to default io.Copy implementation.
167 // Use wrapper to hide w.ReadFrom from io.Copy.
168 return io.Copy(writerOnly{w}, src)
171 // noLimit is an effective infinite upper bound for io.LimitedReader
172 const noLimit int64 = (1 << 63) - 1
174 // Create new connection from rwc.
175 func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
177 c.remoteAddr = rwc.RemoteAddr().String()
180 c.body = make([]byte, sniffLen)
181 c.lr = io.LimitReader(rwc, noLimit).(*io.LimitedReader)
182 br := bufio.NewReader(c.lr)
183 bw := bufio.NewWriter(rwc)
184 c.buf = bufio.NewReadWriter(br, bw)
188 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
189 // in an HTTP request.
190 // This can be overridden by setting Server.MaxHeaderBytes.
191 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
193 func (srv *Server) maxHeaderBytes() int {
194 if srv.MaxHeaderBytes > 0 {
195 return srv.MaxHeaderBytes
197 return DefaultMaxHeaderBytes
200 // wrapper around io.ReaderCloser which on first read, sends an
201 // HTTP/1.1 100 Continue header
202 type expectContinueReader struct {
204 readCloser io.ReadCloser
208 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
210 return 0, errors.New("http: Read after Close on request Body")
212 if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked {
213 ecr.resp.wroteContinue = true
214 io.WriteString(ecr.resp.conn.buf, "HTTP/1.1 100 Continue\r\n\r\n")
215 ecr.resp.conn.buf.Flush()
217 return ecr.readCloser.Read(p)
220 func (ecr *expectContinueReader) Close() error {
222 return ecr.readCloser.Close()
225 // TimeFormat is the time format to use with
226 // time.Parse and time.Time.Format when parsing
227 // or generating times in HTTP headers.
228 // It is like time.RFC1123 but hard codes GMT as the time zone.
229 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
231 var errTooLarge = errors.New("http: request too large")
233 // Read next request from connection.
234 func (c *conn) readRequest() (w *response, err error) {
236 return nil, ErrHijacked
238 c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
240 if req, err = ReadRequest(c.buf.Reader); err != nil {
242 return nil, errTooLarge
248 req.RemoteAddr = c.remoteAddr
254 w.header = make(Header)
260 func (w *response) Header() Header {
264 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
265 // consumed by a handler that the server will read from the client
266 // in order to keep a connection alive. If there are more bytes than
267 // this then the server to be paranoid instead sends a "Connection:
270 // This number is approximately what a typical machine's TCP buffer
271 // size is anyway. (if we have the bytes on the machine, we might as
273 const maxPostHandlerReadBytes = 256 << 10
275 func (w *response) WriteHeader(code int) {
277 log.Print("http: response.WriteHeader on hijacked connection")
281 log.Print("http: multiple response.WriteHeader calls")
287 // Check for a explicit (and valid) Content-Length header.
289 var contentLength int64
290 if clenStr := w.header.Get("Content-Length"); clenStr != "" {
292 contentLength, err = strconv.ParseInt(clenStr, 10, 64)
296 log.Printf("http: invalid Content-Length of %q sent", clenStr)
297 w.header.Del("Content-Length")
301 if w.req.wantsHttp10KeepAlive() && (w.req.Method == "HEAD" || hasCL) {
302 _, connectionHeaderSet := w.header["Connection"]
303 if !connectionHeaderSet {
304 w.header.Set("Connection", "keep-alive")
306 } else if !w.req.ProtoAtLeast(1, 1) {
307 // Client did not ask to keep connection alive.
308 w.closeAfterReply = true
311 if w.header.Get("Connection") == "close" {
312 w.closeAfterReply = true
315 // Per RFC 2616, we should consume the request body before
316 // replying, if the handler hasn't already done so. But we
317 // don't want to do an unbounded amount of reading here for
318 // DoS reasons, so we only try up to a threshold.
319 if w.req.ContentLength != 0 && !w.closeAfterReply {
320 ecr, isExpecter := w.req.Body.(*expectContinueReader)
321 if !isExpecter || ecr.resp.wroteContinue {
322 n, _ := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1)
323 if n >= maxPostHandlerReadBytes {
325 w.header.Set("Connection", "close")
332 if code == StatusNotModified {
333 // Must not have body.
334 for _, header := range []string{"Content-Type", "Content-Length", "Transfer-Encoding"} {
335 if w.header.Get(header) != "" {
336 // TODO: return an error if WriteHeader gets a return parameter
337 // or set a flag on w to make future Writes() write an error page?
338 // for now just log and drop the header.
339 log.Printf("http: StatusNotModified response with header %q defined", header)
344 // If no content type, apply sniffing algorithm to body.
345 if w.header.Get("Content-Type") == "" && w.req.Method != "HEAD" {
350 if _, ok := w.header["Date"]; !ok {
351 w.Header().Set("Date", time.Now().UTC().Format(TimeFormat))
354 te := w.header.Get("Transfer-Encoding")
356 if hasCL && hasTE && te != "identity" {
357 // TODO: return an error if WriteHeader gets a return parameter
358 // For now just ignore the Content-Length.
359 log.Printf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
361 w.header.Del("Content-Length")
365 if w.req.Method == "HEAD" || code == StatusNotModified {
368 w.contentLength = contentLength
369 w.header.Del("Transfer-Encoding")
370 } else if w.req.ProtoAtLeast(1, 1) {
371 // HTTP/1.1 or greater: use chunked transfer encoding
372 // to avoid closing the connection at EOF.
373 // TODO: this blows away any custom or stacked Transfer-Encoding they
374 // might have set. Deal with that as need arises once we have a valid
377 w.header.Set("Transfer-Encoding", "chunked")
379 // HTTP version < 1.1: cannot do chunked transfer
380 // encoding and we don't know the Content-Length so
381 // signal EOF by closing connection.
382 w.closeAfterReply = true
383 w.header.Del("Transfer-Encoding") // in case already set
386 // Cannot use Content-Length with non-identity Transfer-Encoding.
388 w.header.Del("Content-Length")
390 if !w.req.ProtoAtLeast(1, 0) {
394 if w.req.ProtoAtLeast(1, 1) {
397 codestring := strconv.Itoa(code)
398 text, ok := statusText[code]
400 text = "status code " + codestring
402 io.WriteString(w.conn.buf, proto+" "+codestring+" "+text+"\r\n")
403 w.header.Write(w.conn.buf)
405 // If we need to sniff the body, leave the header open.
406 // Otherwise, end it here.
408 io.WriteString(w.conn.buf, "\r\n")
412 // sniff uses the first block of written data,
413 // stored in w.conn.body, to decide the Content-Type
414 // for the HTTP body.
415 func (w *response) sniff() {
422 fmt.Fprintf(w.conn.buf, "Content-Type: %s\r\n\r\n", DetectContentType(data))
428 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data))
430 _, err := w.conn.buf.Write(data)
431 if w.chunking && err == nil {
432 io.WriteString(w.conn.buf, "\r\n")
436 // bodyAllowed returns true if a Write is allowed for this response type.
437 // It's illegal to call this before the header has been flushed.
438 func (w *response) bodyAllowed() bool {
442 return w.status != StatusNotModified && w.req.Method != "HEAD"
445 func (w *response) Write(data []byte) (n int, err error) {
447 log.Print("http: response.Write on hijacked connection")
448 return 0, ErrHijacked
451 w.WriteHeader(StatusOK)
456 if !w.bodyAllowed() {
457 return 0, ErrBodyNotAllowed
460 w.written += int64(len(data)) // ignoring errors, for errorKludge
461 if w.contentLength != -1 && w.written > w.contentLength {
462 return 0, ErrContentLength
467 // We need to sniff the beginning of the output to
468 // determine the content type. Accumulate the
469 // initial writes in w.conn.body.
470 // Cap m so that append won't allocate.
471 m = cap(w.conn.body) - len(w.conn.body)
475 w.conn.body = append(w.conn.body, data[:m]...)
478 // Copied everything into the buffer.
479 // Wait for next write.
483 // Filled the buffer; more data remains.
484 // Sniff the content (flushes the buffer)
485 // and then proceed with the remainder
486 // of the data as a normal Write.
487 // Calling sniff clears needSniff.
491 // TODO(rsc): if chunking happened after the buffering,
492 // then there would be fewer chunk headers.
493 // On the other hand, it would make hijacking more difficult.
495 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data)) // TODO(rsc): use strconv not fmt
497 n, err = w.conn.buf.Write(data)
498 if err == nil && w.chunking {
500 err = io.ErrShortWrite
503 io.WriteString(w.conn.buf, "\r\n")
510 func (w *response) finishRequest() {
511 // If this was an HTTP/1.0 request with keep-alive and we sent a Content-Length
512 // back, we can make this a keep-alive response ...
513 if w.req.wantsHttp10KeepAlive() {
514 sentLength := w.header.Get("Content-Length") != ""
515 if sentLength && w.header.Get("Connection") == "keep-alive" {
516 w.closeAfterReply = false
520 w.WriteHeader(StatusOK)
526 io.WriteString(w.conn.buf, "0\r\n")
527 // trailer key/value pairs, followed by blank line
528 io.WriteString(w.conn.buf, "\r\n")
531 // Close the body, unless we're about to close the whole TCP connection
533 if !w.closeAfterReply {
536 if w.req.MultipartForm != nil {
537 w.req.MultipartForm.RemoveAll()
540 if w.contentLength != -1 && w.contentLength != w.written {
541 // Did not write enough. Avoid getting out of sync.
542 w.closeAfterReply = true
546 func (w *response) Flush() {
548 w.WriteHeader(StatusOK)
554 // Close the connection.
555 func (c *conn) close() {
566 // Serve a new connection.
567 func (c *conn) serve() {
575 fmt.Fprintf(&buf, "http: panic serving %v: %v\n", c.remoteAddr, err)
576 buf.Write(debug.Stack())
577 log.Print(buf.String())
579 if c.rwc != nil { // may be nil if connection hijacked
584 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
585 if err := tlsConn.Handshake(); err != nil {
589 c.tlsState = new(tls.ConnectionState)
590 *c.tlsState = tlsConn.ConnectionState()
594 w, err := c.readRequest()
596 msg := "400 Bad Request"
597 if err == errTooLarge {
598 // Their HTTP client may or may not be
599 // able to read this if we're
600 // responding to them and hanging up
601 // while they're still writing their
602 // request. Undefined behavior.
603 msg = "413 Request Entity Too Large"
604 } else if err == io.EOF {
606 } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
609 fmt.Fprintf(c.rwc, "HTTP/1.1 %s\r\n\r\n", msg)
613 // Expect 100 Continue support
615 if req.expectsContinue() {
616 if req.ProtoAtLeast(1, 1) {
617 // Wrap the Body reader with one that replies on the connection
618 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
620 if req.ContentLength == 0 {
621 w.Header().Set("Connection", "close")
622 w.WriteHeader(StatusBadRequest)
626 req.Header.Del("Expect")
627 } else if req.Header.Get("Expect") != "" {
628 // TODO(bradfitz): let ServeHTTP handlers handle
629 // requests with non-standard expectation[s]? Seems
630 // theoretical at best, and doesn't fit into the
631 // current ServeHTTP model anyway. We'd need to
632 // make the ResponseWriter an optional
633 // "ExpectReplier" interface or something.
635 // For now we'll just obey RFC 2616 14.20 which says
636 // "If a server receives a request containing an
637 // Expect field that includes an expectation-
638 // extension that it does not support, it MUST
639 // respond with a 417 (Expectation Failed) status."
640 w.Header().Set("Connection", "close")
641 w.WriteHeader(StatusExpectationFailed)
646 handler := c.server.Handler
648 handler = DefaultServeMux
651 // HTTP cannot have multiple simultaneous active requests.[*]
652 // Until the server replies to this request, it can't read another,
653 // so we might as well run the handler in this goroutine.
654 // [*] Not strictly true: HTTP pipelining. We could let them all process
655 // in parallel even if their responses need to be serialized.
656 handler.ServeHTTP(w, w.req)
661 if w.closeAfterReply {
668 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
670 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
672 return nil, nil, ErrHijacked
674 w.conn.hijacked = true
682 // The HandlerFunc type is an adapter to allow the use of
683 // ordinary functions as HTTP handlers. If f is a function
684 // with the appropriate signature, HandlerFunc(f) is a
685 // Handler object that calls f.
686 type HandlerFunc func(ResponseWriter, *Request)
688 // ServeHTTP calls f(w, r).
689 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
695 // Error replies to the request with the specified error message and HTTP code.
696 func Error(w ResponseWriter, error string, code int) {
697 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
699 fmt.Fprintln(w, error)
702 // NotFound replies to the request with an HTTP 404 not found error.
703 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
705 // NotFoundHandler returns a simple request handler
706 // that replies to each request with a ``404 page not found'' reply.
707 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
709 // StripPrefix returns a handler that serves HTTP requests
710 // by removing the given prefix from the request URL's Path
711 // and invoking the handler h. StripPrefix handles a
712 // request for a path that doesn't begin with prefix by
713 // replying with an HTTP 404 not found error.
714 func StripPrefix(prefix string, h Handler) Handler {
715 return HandlerFunc(func(w ResponseWriter, r *Request) {
716 if !strings.HasPrefix(r.URL.Path, prefix) {
720 r.URL.Path = r.URL.Path[len(prefix):]
725 // Redirect replies to the request with a redirect to url,
726 // which may be a path relative to the request path.
727 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
728 if u, err := url.Parse(urlStr); err == nil {
729 // If url was relative, make absolute by
730 // combining with request path.
731 // The browser would probably do this for us,
732 // but doing it ourselves is more reliable.
734 // NOTE(rsc): RFC 2616 says that the Location
735 // line must be an absolute URI, like
736 // "http://www.google.com/redirect/",
737 // not a path like "/redirect/".
738 // Unfortunately, we don't know what to
739 // put in the host name section to get the
740 // client to connect to us again, so we can't
741 // know the right absolute URI to send back.
742 // Because of this problem, no one pays attention
743 // to the RFC; they all send back just a new path.
745 oldpath := r.URL.Path
746 if oldpath == "" { // should not happen, but avoid a crash if it does
750 // no leading http://server
751 if urlStr == "" || urlStr[0] != '/' {
752 // make relative path absolute
753 olddir, _ := path.Split(oldpath)
754 urlStr = olddir + urlStr
758 if i := strings.Index(urlStr, "?"); i != -1 {
759 urlStr, query = urlStr[:i], urlStr[i:]
762 // clean up but preserve trailing slash
763 trailing := urlStr[len(urlStr)-1] == '/'
764 urlStr = path.Clean(urlStr)
765 if trailing && urlStr[len(urlStr)-1] != '/' {
772 w.Header().Set("Location", urlStr)
775 // RFC2616 recommends that a short note "SHOULD" be included in the
776 // response because older user agents may not understand 301/307.
777 // Shouldn't send the response for POST or HEAD; that leaves GET.
778 if r.Method == "GET" {
779 note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
780 fmt.Fprintln(w, note)
784 var htmlReplacer = strings.NewReplacer(
788 // """ is shorter than """.
790 // "'" is shorter than "'" and apos was not in HTML until HTML5.
794 func htmlEscape(s string) string {
795 return htmlReplacer.Replace(s)
798 // Redirect to a fixed URL
799 type redirectHandler struct {
804 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
805 Redirect(w, r, rh.url, rh.code)
808 // RedirectHandler returns a request handler that redirects
809 // each request it receives to the given url using the given
811 func RedirectHandler(url string, code int) Handler {
812 return &redirectHandler{url, code}
815 // ServeMux is an HTTP request multiplexer.
816 // It matches the URL of each incoming request against a list of registered
817 // patterns and calls the handler for the pattern that
818 // most closely matches the URL.
820 // Patterns named fixed, rooted paths, like "/favicon.ico",
821 // or rooted subtrees, like "/images/" (note the trailing slash).
822 // Longer patterns take precedence over shorter ones, so that
823 // if there are handlers registered for both "/images/"
824 // and "/images/thumbnails/", the latter handler will be
825 // called for paths beginning "/images/thumbnails/" and the
826 // former will receiver requests for any other paths in the
827 // "/images/" subtree.
829 // Patterns may optionally begin with a host name, restricting matches to
830 // URLs on that host only. Host-specific patterns take precedence over
831 // general patterns, so that a handler might register for the two patterns
832 // "/codesearch" and "codesearch.google.com/" without also taking over
833 // requests for "http://www.google.com/".
835 // ServeMux also takes care of sanitizing the URL request path,
836 // redirecting any request containing . or .. elements to an
837 // equivalent .- and ..-free URL.
838 type ServeMux struct {
840 m map[string]muxEntry
843 type muxEntry struct {
848 // NewServeMux allocates and returns a new ServeMux.
849 func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} }
851 // DefaultServeMux is the default ServeMux used by Serve.
852 var DefaultServeMux = NewServeMux()
854 // Does path match pattern?
855 func pathMatch(pattern, path string) bool {
856 if len(pattern) == 0 {
861 if pattern[n-1] != '/' {
862 return pattern == path
864 return len(path) >= n && path[0:n] == pattern
867 // Return the canonical path for p, eliminating . and .. elements.
868 func cleanPath(p string) string {
876 // path.Clean removes trailing slash except for root;
877 // put the trailing slash back if necessary.
878 if p[len(p)-1] == '/' && np != "/" {
884 // Find a handler on a handler map given a path string
885 // Most-specific (longest) pattern wins
886 func (mux *ServeMux) match(path string) Handler {
889 for k, v := range mux.m {
890 if !pathMatch(k, path) {
893 if h == nil || len(k) > n {
901 // handler returns the handler to use for the request r.
902 func (mux *ServeMux) handler(r *Request) Handler {
904 defer mux.mu.RUnlock()
906 // Host-specific pattern takes precedence over generic ones
907 h := mux.match(r.Host + r.URL.Path)
909 h = mux.match(r.URL.Path)
912 h = NotFoundHandler()
917 // ServeHTTP dispatches the request to the handler whose
918 // pattern most closely matches the request URL.
919 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
920 // Clean path to canonical form and redirect.
921 if p := cleanPath(r.URL.Path); p != r.URL.Path {
922 w.Header().Set("Location", p)
923 w.WriteHeader(StatusMovedPermanently)
926 mux.handler(r).ServeHTTP(w, r)
929 // Handle registers the handler for the given pattern.
930 // If a handler already exists for pattern, Handle panics.
931 func (mux *ServeMux) Handle(pattern string, handler Handler) {
933 defer mux.mu.Unlock()
936 panic("http: invalid pattern " + pattern)
939 panic("http: nil handler")
941 if mux.m[pattern].explicit {
942 panic("http: multiple registrations for " + pattern)
945 mux.m[pattern] = muxEntry{explicit: true, h: handler}
948 // If pattern is /tree/, insert an implicit permanent redirect for /tree.
949 // It can be overridden by an explicit registration.
951 if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
952 mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(pattern, StatusMovedPermanently)}
956 // HandleFunc registers the handler function for the given pattern.
957 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
958 mux.Handle(pattern, HandlerFunc(handler))
961 // Handle registers the handler for the given pattern
962 // in the DefaultServeMux.
963 // The documentation for ServeMux explains how patterns are matched.
964 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
966 // HandleFunc registers the handler function for the given pattern
967 // in the DefaultServeMux.
968 // The documentation for ServeMux explains how patterns are matched.
969 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
970 DefaultServeMux.HandleFunc(pattern, handler)
973 // Serve accepts incoming HTTP connections on the listener l,
974 // creating a new service thread for each. The service threads
975 // read requests and then call handler to reply to them.
976 // Handler is typically nil, in which case the DefaultServeMux is used.
977 func Serve(l net.Listener, handler Handler) error {
978 srv := &Server{Handler: handler}
982 // A Server defines parameters for running an HTTP server.
984 Addr string // TCP address to listen on, ":http" if empty
985 Handler Handler // handler to invoke, http.DefaultServeMux if nil
986 ReadTimeout time.Duration // maximum duration before timing out read of the request
987 WriteTimeout time.Duration // maximum duration before timing out write of the response
988 MaxHeaderBytes int // maximum size of request headers, DefaultMaxHeaderBytes if 0
989 TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
992 // ListenAndServe listens on the TCP network address srv.Addr and then
993 // calls Serve to handle requests on incoming connections. If
994 // srv.Addr is blank, ":http" is used.
995 func (srv *Server) ListenAndServe() error {
1000 l, e := net.Listen("tcp", addr)
1007 // Serve accepts incoming connections on the Listener l, creating a
1008 // new service thread for each. The service threads read requests and
1009 // then call srv.Handler to reply to them.
1010 func (srv *Server) Serve(l net.Listener) error {
1012 var tempDelay time.Duration // how long to sleep on accept failure
1016 if ne, ok := e.(net.Error); ok && ne.Temporary() {
1018 tempDelay = 5 * time.Millisecond
1022 if max := 1 * time.Second; tempDelay > max {
1025 log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay)
1026 time.Sleep(tempDelay)
1032 if srv.ReadTimeout != 0 {
1033 rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
1035 if srv.WriteTimeout != 0 {
1036 rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
1038 c, err := srv.newConn(rw)
1044 panic("not reached")
1047 // ListenAndServe listens on the TCP network address addr
1048 // and then calls Serve with handler to handle requests
1049 // on incoming connections. Handler is typically nil,
1050 // in which case the DefaultServeMux is used.
1052 // A trivial example server is:
1062 // // hello world, the web server
1063 // func HelloServer(w http.ResponseWriter, req *http.Request) {
1064 // io.WriteString(w, "hello, world!\n")
1068 // http.HandleFunc("/hello", HelloServer)
1069 // err := http.ListenAndServe(":12345", nil)
1071 // log.Fatal("ListenAndServe: ", err)
1074 func ListenAndServe(addr string, handler Handler) error {
1075 server := &Server{Addr: addr, Handler: handler}
1076 return server.ListenAndServe()
1079 // ListenAndServeTLS acts identically to ListenAndServe, except that it
1080 // expects HTTPS connections. Additionally, files containing a certificate and
1081 // matching private key for the server must be provided. If the certificate
1082 // is signed by a certificate authority, the certFile should be the concatenation
1083 // of the server's certificate followed by the CA's certificate.
1085 // A trivial example server is:
1092 // func handler(w http.ResponseWriter, req *http.Request) {
1093 // w.Header().Set("Content-Type", "text/plain")
1094 // w.Write([]byte("This is an example server.\n"))
1098 // http.HandleFunc("/", handler)
1099 // log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
1100 // err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
1106 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
1107 func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
1108 server := &Server{Addr: addr, Handler: handler}
1109 return server.ListenAndServeTLS(certFile, keyFile)
1112 // ListenAndServeTLS listens on the TCP network address srv.Addr and
1113 // then calls Serve to handle requests on incoming TLS connections.
1115 // Filenames containing a certificate and matching private key for
1116 // the server must be provided. If the certificate is signed by a
1117 // certificate authority, the certFile should be the concatenation
1118 // of the server's certificate followed by the CA's certificate.
1120 // If srv.Addr is blank, ":https" is used.
1121 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
1126 config := &tls.Config{}
1127 if srv.TLSConfig != nil {
1128 *config = *srv.TLSConfig
1130 if config.NextProtos == nil {
1131 config.NextProtos = []string{"http/1.1"}
1135 config.Certificates = make([]tls.Certificate, 1)
1136 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
1141 conn, err := net.Listen("tcp", addr)
1146 tlsListener := tls.NewListener(conn, config)
1147 return srv.Serve(tlsListener)
1150 // TimeoutHandler returns a Handler that runs h with the given time limit.
1152 // The new Handler calls h.ServeHTTP to handle each request, but if a
1153 // call runs for more than ns nanoseconds, the handler responds with
1154 // a 503 Service Unavailable error and the given message in its body.
1155 // (If msg is empty, a suitable default message will be sent.)
1156 // After such a timeout, writes by h to its ResponseWriter will return
1157 // ErrHandlerTimeout.
1158 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
1159 f := func() <-chan time.Time {
1160 return time.After(dt)
1162 return &timeoutHandler{h, f, msg}
1165 // ErrHandlerTimeout is returned on ResponseWriter Write calls
1166 // in handlers which have timed out.
1167 var ErrHandlerTimeout = errors.New("http: Handler timeout")
1169 type timeoutHandler struct {
1171 timeout func() <-chan time.Time // returns channel producing a timeout
1175 func (h *timeoutHandler) errorBody() string {
1179 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
1182 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
1183 done := make(chan bool)
1184 tw := &timeoutWriter{w: w}
1186 h.handler.ServeHTTP(tw, r)
1194 defer tw.mu.Unlock()
1195 if !tw.wroteHeader {
1196 tw.w.WriteHeader(StatusServiceUnavailable)
1197 tw.w.Write([]byte(h.errorBody()))
1203 type timeoutWriter struct {
1211 func (tw *timeoutWriter) Header() Header {
1212 return tw.w.Header()
1215 func (tw *timeoutWriter) Write(p []byte) (int, error) {
1217 timedOut := tw.timedOut
1220 return 0, ErrHandlerTimeout
1222 return tw.w.Write(p)
1225 func (tw *timeoutWriter) WriteHeader(code int) {
1227 if tw.timedOut || tw.wroteHeader {
1231 tw.wroteHeader = true
1233 tw.w.WriteHeader(code)