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.
32 // Errors introduced by the HTTP server.
34 ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
35 ErrBodyNotAllowed = errors.New("http: response status code does not allow body")
36 ErrHijacked = errors.New("Conn has been hijacked")
37 ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length")
40 // Objects implementing the Handler interface can be
41 // registered to serve a particular path or subtree
42 // in the HTTP server.
44 // ServeHTTP should write reply headers and data to the ResponseWriter
45 // and then return. Returning signals that the request is finished
46 // and that the HTTP server can move on to the next request on
48 type Handler interface {
49 ServeHTTP(ResponseWriter, *Request)
52 // A ResponseWriter interface is used by an HTTP handler to
53 // construct an HTTP response.
54 type ResponseWriter interface {
55 // Header returns the header map that will be sent by WriteHeader.
56 // Changing the header after a call to WriteHeader (or Write) has
60 // Write writes the data to the connection as part of an HTTP reply.
61 // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
62 // before writing the data.
63 Write([]byte) (int, error)
65 // WriteHeader sends an HTTP response header with status code.
66 // If WriteHeader is not called explicitly, the first call to Write
67 // will trigger an implicit WriteHeader(http.StatusOK).
68 // Thus explicit calls to WriteHeader are mainly used to
73 // The Flusher interface is implemented by ResponseWriters that allow
74 // an HTTP handler to flush buffered data to the client.
76 // Note that even for ResponseWriters that support Flush,
77 // if the client is connected through an HTTP proxy,
78 // the buffered data may not reach the client until the response
80 type Flusher interface {
81 // Flush sends any buffered data to the client.
85 // The Hijacker interface is implemented by ResponseWriters that allow
86 // an HTTP handler to take over the connection.
87 type Hijacker interface {
88 // Hijack lets the caller take over the connection.
89 // After a call to Hijack(), the HTTP server library
90 // will not do anything else with the connection.
91 // It becomes the caller's responsibility to manage
92 // and close the connection.
93 Hijack() (net.Conn, *bufio.ReadWriter, error)
96 // A conn represents the server side of an HTTP connection.
98 remoteAddr string // network address of remote side
99 server *Server // the Server on which the connection arrived
100 rwc net.Conn // i/o connection
101 lr *io.LimitedReader // io.LimitReader(rwc)
102 buf *bufio.ReadWriter // buffered(lr,rwc), reading from bufio->limitReader->rwc
103 hijacked bool // connection has been hijacked by handler
104 tlsState *tls.ConnectionState // or nil when not using TLS
108 // A response represents the server side of an HTTP response.
109 type response struct {
111 req *Request // request for this response
112 chunking bool // using chunked transfer encoding for reply body
113 wroteHeader bool // reply header has been written
114 wroteContinue bool // 100 Continue response was written
115 header Header // reply header parameters
116 written int64 // number of bytes written in body
117 contentLength int64 // explicitly-declared Content-Length; or -1
118 status int // status code passed to WriteHeader
119 needSniff bool // need to sniff to find Content-Type
121 // close connection after this reply. set on request and
122 // updated after response from handler if there's a
123 // "Connection: keep-alive" response header and a
127 // requestBodyLimitHit is set by requestTooLarge when
128 // maxBytesReader hits its max size. It is checked in
129 // WriteHeader, to make sure we don't consume the the
130 // remaining request body to try to advance to the next HTTP
131 // request. Instead, when this is set, we stop doing
132 // subsequent requests on this connection and stop reading
134 requestBodyLimitHit bool
137 // requestTooLarge is called by maxBytesReader when too much input has
138 // been read from the client.
139 func (w *response) requestTooLarge() {
140 w.closeAfterReply = true
141 w.requestBodyLimitHit = true
143 w.Header().Set("Connection", "close")
147 type writerOnly struct {
151 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
152 // Flush before checking w.chunking, as Flush will call
153 // WriteHeader if it hasn't been called yet, and WriteHeader
154 // is what sets w.chunking.
156 if !w.chunking && w.bodyAllowed() && !w.needSniff {
157 if rf, ok := w.conn.rwc.(io.ReaderFrom); ok {
158 n, err = rf.ReadFrom(src)
163 // Fall back to default io.Copy implementation.
164 // Use wrapper to hide w.ReadFrom from io.Copy.
165 return io.Copy(writerOnly{w}, src)
168 // noLimit is an effective infinite upper bound for io.LimitedReader
169 const noLimit int64 = (1 << 63) - 1
171 // Create new connection from rwc.
172 func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
174 c.remoteAddr = rwc.RemoteAddr().String()
177 c.body = make([]byte, sniffLen)
178 c.lr = io.LimitReader(rwc, noLimit).(*io.LimitedReader)
179 br := bufio.NewReader(c.lr)
180 bw := bufio.NewWriter(rwc)
181 c.buf = bufio.NewReadWriter(br, bw)
185 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
186 // in an HTTP request.
187 // This can be overridden by setting Server.MaxHeaderBytes.
188 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
190 func (srv *Server) maxHeaderBytes() int {
191 if srv.MaxHeaderBytes > 0 {
192 return srv.MaxHeaderBytes
194 return DefaultMaxHeaderBytes
197 // wrapper around io.ReaderCloser which on first read, sends an
198 // HTTP/1.1 100 Continue header
199 type expectContinueReader struct {
201 readCloser io.ReadCloser
205 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
207 return 0, errors.New("http: Read after Close on request Body")
209 if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked {
210 ecr.resp.wroteContinue = true
211 io.WriteString(ecr.resp.conn.buf, "HTTP/1.1 100 Continue\r\n\r\n")
212 ecr.resp.conn.buf.Flush()
214 return ecr.readCloser.Read(p)
217 func (ecr *expectContinueReader) Close() error {
219 return ecr.readCloser.Close()
222 // TimeFormat is the time format to use with
223 // time.Parse and time.Time.Format when parsing
224 // or generating times in HTTP headers.
225 // It is like time.RFC1123 but hard codes GMT as the time zone.
226 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
228 var errTooLarge = errors.New("http: request too large")
230 // Read next request from connection.
231 func (c *conn) readRequest() (w *response, err error) {
233 return nil, ErrHijacked
235 c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
237 if req, err = ReadRequest(c.buf.Reader); err != nil {
239 return nil, errTooLarge
245 req.RemoteAddr = c.remoteAddr
251 w.header = make(Header)
257 func (w *response) Header() Header {
261 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
262 // consumed by a handler that the server will read from the a client
263 // in order to keep a connection alive. If there are more bytes than
264 // this then the server to be paranoid instead sends a "Connection:
267 // This number is approximately what a typical machine's TCP buffer
268 // size is anyway. (if we have the bytes on the machine, we might as
270 const maxPostHandlerReadBytes = 256 << 10
272 func (w *response) WriteHeader(code int) {
274 log.Print("http: response.WriteHeader on hijacked connection")
278 log.Print("http: multiple response.WriteHeader calls")
284 // Check for a explicit (and valid) Content-Length header.
286 var contentLength int64
287 if clenStr := w.header.Get("Content-Length"); clenStr != "" {
289 contentLength, err = strconv.Atoi64(clenStr)
293 log.Printf("http: invalid Content-Length of %q sent", clenStr)
294 w.header.Del("Content-Length")
298 if w.req.wantsHttp10KeepAlive() && (w.req.Method == "HEAD" || hasCL) {
299 _, connectionHeaderSet := w.header["Connection"]
300 if !connectionHeaderSet {
301 w.header.Set("Connection", "keep-alive")
303 } else if !w.req.ProtoAtLeast(1, 1) {
304 // Client did not ask to keep connection alive.
305 w.closeAfterReply = true
308 if w.header.Get("Connection") == "close" {
309 w.closeAfterReply = true
312 // Per RFC 2616, we should consume the request body before
313 // replying, if the handler hasn't already done so. But we
314 // don't want to do an unbounded amount of reading here for
315 // DoS reasons, so we only try up to a threshold.
316 if w.req.ContentLength != 0 && !w.closeAfterReply {
317 ecr, isExpecter := w.req.Body.(*expectContinueReader)
318 if !isExpecter || ecr.resp.wroteContinue {
319 n, _ := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1)
320 if n >= maxPostHandlerReadBytes {
322 w.header.Set("Connection", "close")
329 if code == StatusNotModified {
330 // Must not have body.
331 for _, header := range []string{"Content-Type", "Content-Length", "Transfer-Encoding"} {
332 if w.header.Get(header) != "" {
333 // TODO: return an error if WriteHeader gets a return parameter
334 // or set a flag on w to make future Writes() write an error page?
335 // for now just log and drop the header.
336 log.Printf("http: StatusNotModified response with header %q defined", header)
341 // If no content type, apply sniffing algorithm to body.
342 if w.header.Get("Content-Type") == "" {
347 if _, ok := w.header["Date"]; !ok {
348 w.Header().Set("Date", time.UTC().Format(TimeFormat))
351 te := w.header.Get("Transfer-Encoding")
353 if hasCL && hasTE && te != "identity" {
354 // TODO: return an error if WriteHeader gets a return parameter
355 // For now just ignore the Content-Length.
356 log.Printf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
358 w.header.Del("Content-Length")
362 if w.req.Method == "HEAD" || code == StatusNotModified {
365 w.contentLength = contentLength
366 w.header.Del("Transfer-Encoding")
367 } else if w.req.ProtoAtLeast(1, 1) {
368 // HTTP/1.1 or greater: use chunked transfer encoding
369 // to avoid closing the connection at EOF.
370 // TODO: this blows away any custom or stacked Transfer-Encoding they
371 // might have set. Deal with that as need arises once we have a valid
374 w.header.Set("Transfer-Encoding", "chunked")
376 // HTTP version < 1.1: cannot do chunked transfer
377 // encoding and we don't know the Content-Length so
378 // signal EOF by closing connection.
379 w.closeAfterReply = true
380 w.header.Del("Transfer-Encoding") // in case already set
383 // Cannot use Content-Length with non-identity Transfer-Encoding.
385 w.header.Del("Content-Length")
387 if !w.req.ProtoAtLeast(1, 0) {
391 if w.req.ProtoAtLeast(1, 1) {
394 codestring := strconv.Itoa(code)
395 text, ok := statusText[code]
397 text = "status code " + codestring
399 io.WriteString(w.conn.buf, proto+" "+codestring+" "+text+"\r\n")
400 w.header.Write(w.conn.buf)
402 // If we need to sniff the body, leave the header open.
403 // Otherwise, end it here.
405 io.WriteString(w.conn.buf, "\r\n")
409 // sniff uses the first block of written data,
410 // stored in w.conn.body, to decide the Content-Type
411 // for the HTTP body.
412 func (w *response) sniff() {
419 fmt.Fprintf(w.conn.buf, "Content-Type: %s\r\n\r\n", DetectContentType(data))
425 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data))
427 _, err := w.conn.buf.Write(data)
428 if w.chunking && err == nil {
429 io.WriteString(w.conn.buf, "\r\n")
433 // bodyAllowed returns true if a Write is allowed for this response type.
434 // It's illegal to call this before the header has been flushed.
435 func (w *response) bodyAllowed() bool {
439 return w.status != StatusNotModified && w.req.Method != "HEAD"
442 func (w *response) Write(data []byte) (n int, err error) {
444 log.Print("http: response.Write on hijacked connection")
445 return 0, ErrHijacked
448 w.WriteHeader(StatusOK)
453 if !w.bodyAllowed() {
454 return 0, ErrBodyNotAllowed
457 w.written += int64(len(data)) // ignoring errors, for errorKludge
458 if w.contentLength != -1 && w.written > w.contentLength {
459 return 0, ErrContentLength
464 // We need to sniff the beginning of the output to
465 // determine the content type. Accumulate the
466 // initial writes in w.conn.body.
467 // Cap m so that append won't allocate.
468 m := cap(w.conn.body) - len(w.conn.body)
472 w.conn.body = append(w.conn.body, data[:m]...)
475 // Copied everything into the buffer.
476 // Wait for next write.
480 // Filled the buffer; more data remains.
481 // Sniff the content (flushes the buffer)
482 // and then proceed with the remainder
483 // of the data as a normal Write.
484 // Calling sniff clears needSniff.
488 // TODO(rsc): if chunking happened after the buffering,
489 // then there would be fewer chunk headers.
490 // On the other hand, it would make hijacking more difficult.
492 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data)) // TODO(rsc): use strconv not fmt
494 n, err = w.conn.buf.Write(data)
495 if err == nil && w.chunking {
497 err = io.ErrShortWrite
500 io.WriteString(w.conn.buf, "\r\n")
507 func (w *response) finishRequest() {
508 // If this was an HTTP/1.0 request with keep-alive and we sent a Content-Length
509 // back, we can make this a keep-alive response ...
510 if w.req.wantsHttp10KeepAlive() {
511 sentLength := w.header.Get("Content-Length") != ""
512 if sentLength && w.header.Get("Connection") == "keep-alive" {
513 w.closeAfterReply = false
517 w.WriteHeader(StatusOK)
523 io.WriteString(w.conn.buf, "0\r\n")
524 // trailer key/value pairs, followed by blank line
525 io.WriteString(w.conn.buf, "\r\n")
528 // Close the body, unless we're about to close the whole TCP connection
530 if !w.closeAfterReply {
533 if w.req.MultipartForm != nil {
534 w.req.MultipartForm.RemoveAll()
537 if w.contentLength != -1 && w.contentLength != w.written {
538 // Did not write enough. Avoid getting out of sync.
539 w.closeAfterReply = true
543 func (w *response) Flush() {
545 w.WriteHeader(StatusOK)
551 // Close the connection.
552 func (c *conn) close() {
563 // Serve a new connection.
564 func (c *conn) serve() {
570 if c.rwc != nil { // may be nil if connection hijacked
575 fmt.Fprintf(&buf, "http: panic serving %v: %v\n", c.remoteAddr, err)
576 buf.Write(debug.Stack())
577 log.Print(buf.String())
580 if tlsConn, ok := c.rwc.(*tls.Conn); ok {
581 if err := tlsConn.Handshake(); err != nil {
585 c.tlsState = new(tls.ConnectionState)
586 *c.tlsState = tlsConn.ConnectionState()
590 w, err := c.readRequest()
592 msg := "400 Bad Request"
593 if err == errTooLarge {
594 // Their HTTP client may or may not be
595 // able to read this if we're
596 // responding to them and hanging up
597 // while they're still writing their
598 // request. Undefined behavior.
599 msg = "413 Request Entity Too Large"
600 } else if err == io.ErrUnexpectedEOF {
602 } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
605 fmt.Fprintf(c.rwc, "HTTP/1.1 %s\r\n\r\n", msg)
609 // Expect 100 Continue support
611 if req.expectsContinue() {
612 if req.ProtoAtLeast(1, 1) {
613 // Wrap the Body reader with one that replies on the connection
614 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
616 if req.ContentLength == 0 {
617 w.Header().Set("Connection", "close")
618 w.WriteHeader(StatusBadRequest)
622 req.Header.Del("Expect")
623 } else if req.Header.Get("Expect") != "" {
624 // TODO(bradfitz): let ServeHTTP handlers handle
625 // requests with non-standard expectation[s]? Seems
626 // theoretical at best, and doesn't fit into the
627 // current ServeHTTP model anyway. We'd need to
628 // make the ResponseWriter an optional
629 // "ExpectReplier" interface or something.
631 // For now we'll just obey RFC 2616 14.20 which says
632 // "If a server receives a request containing an
633 // Expect field that includes an expectation-
634 // extension that it does not support, it MUST
635 // respond with a 417 (Expectation Failed) status."
636 w.Header().Set("Connection", "close")
637 w.WriteHeader(StatusExpectationFailed)
642 handler := c.server.Handler
644 handler = DefaultServeMux
647 // HTTP cannot have multiple simultaneous active requests.[*]
648 // Until the server replies to this request, it can't read another,
649 // so we might as well run the handler in this goroutine.
650 // [*] Not strictly true: HTTP pipelining. We could let them all process
651 // in parallel even if their responses need to be serialized.
652 handler.ServeHTTP(w, w.req)
657 if w.closeAfterReply {
664 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
666 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
668 return nil, nil, ErrHijacked
670 w.conn.hijacked = true
678 // The HandlerFunc type is an adapter to allow the use of
679 // ordinary functions as HTTP handlers. If f is a function
680 // with the appropriate signature, HandlerFunc(f) is a
681 // Handler object that calls f.
682 type HandlerFunc func(ResponseWriter, *Request)
684 // ServeHTTP calls f(w, r).
685 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
691 // Error replies to the request with the specified error message and HTTP code.
692 func Error(w ResponseWriter, error string, code int) {
693 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
695 fmt.Fprintln(w, error)
698 // NotFound replies to the request with an HTTP 404 not found error.
699 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
701 // NotFoundHandler returns a simple request handler
702 // that replies to each request with a ``404 page not found'' reply.
703 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
705 // StripPrefix returns a handler that serves HTTP requests
706 // by removing the given prefix from the request URL's Path
707 // and invoking the handler h. StripPrefix handles a
708 // request for a path that doesn't begin with prefix by
709 // replying with an HTTP 404 not found error.
710 func StripPrefix(prefix string, h Handler) Handler {
711 return HandlerFunc(func(w ResponseWriter, r *Request) {
712 if !strings.HasPrefix(r.URL.Path, prefix) {
716 r.URL.Path = r.URL.Path[len(prefix):]
721 // Redirect replies to the request with a redirect to url,
722 // which may be a path relative to the request path.
723 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
724 if u, err := url.Parse(urlStr); err == nil {
725 // If url was relative, make absolute by
726 // combining with request path.
727 // The browser would probably do this for us,
728 // but doing it ourselves is more reliable.
730 // NOTE(rsc): RFC 2616 says that the Location
731 // line must be an absolute URI, like
732 // "http://www.google.com/redirect/",
733 // not a path like "/redirect/".
734 // Unfortunately, we don't know what to
735 // put in the host name section to get the
736 // client to connect to us again, so we can't
737 // know the right absolute URI to send back.
738 // Because of this problem, no one pays attention
739 // to the RFC; they all send back just a new path.
741 oldpath := r.URL.Path
742 if oldpath == "" { // should not happen, but avoid a crash if it does
746 // no leading http://server
747 if urlStr == "" || urlStr[0] != '/' {
748 // make relative path absolute
749 olddir, _ := path.Split(oldpath)
750 urlStr = olddir + urlStr
754 if i := strings.Index(urlStr, "?"); i != -1 {
755 urlStr, query = urlStr[:i], urlStr[i:]
758 // clean up but preserve trailing slash
759 trailing := urlStr[len(urlStr)-1] == '/'
760 urlStr = path.Clean(urlStr)
761 if trailing && urlStr[len(urlStr)-1] != '/' {
768 w.Header().Set("Location", urlStr)
771 // RFC2616 recommends that a short note "SHOULD" be included in the
772 // response because older user agents may not understand 301/307.
773 // Shouldn't send the response for POST or HEAD; that leaves GET.
774 if r.Method == "GET" {
775 note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
776 fmt.Fprintln(w, note)
780 var htmlReplacer = strings.NewReplacer(
788 func htmlEscape(s string) string {
789 return htmlReplacer.Replace(s)
792 // Redirect to a fixed URL
793 type redirectHandler struct {
798 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
799 Redirect(w, r, rh.url, rh.code)
802 // RedirectHandler returns a request handler that redirects
803 // each request it receives to the given url using the given
805 func RedirectHandler(url string, code int) Handler {
806 return &redirectHandler{url, code}
809 // ServeMux is an HTTP request multiplexer.
810 // It matches the URL of each incoming request against a list of registered
811 // patterns and calls the handler for the pattern that
812 // most closely matches the URL.
814 // Patterns named fixed, rooted paths, like "/favicon.ico",
815 // or rooted subtrees, like "/images/" (note the trailing slash).
816 // Longer patterns take precedence over shorter ones, so that
817 // if there are handlers registered for both "/images/"
818 // and "/images/thumbnails/", the latter handler will be
819 // called for paths beginning "/images/thumbnails/" and the
820 // former will receiver requests for any other paths in the
821 // "/images/" subtree.
823 // Patterns may optionally begin with a host name, restricting matches to
824 // URLs on that host only. Host-specific patterns take precedence over
825 // general patterns, so that a handler might register for the two patterns
826 // "/codesearch" and "codesearch.google.com/" without also taking over
827 // requests for "http://www.google.com/".
829 // ServeMux also takes care of sanitizing the URL request path,
830 // redirecting any request containing . or .. elements to an
831 // equivalent .- and ..-free URL.
832 type ServeMux struct {
836 // NewServeMux allocates and returns a new ServeMux.
837 func NewServeMux() *ServeMux { return &ServeMux{make(map[string]Handler)} }
839 // DefaultServeMux is the default ServeMux used by Serve.
840 var DefaultServeMux = NewServeMux()
842 // Does path match pattern?
843 func pathMatch(pattern, path string) bool {
844 if len(pattern) == 0 {
849 if pattern[n-1] != '/' {
850 return pattern == path
852 return len(path) >= n && path[0:n] == pattern
855 // Return the canonical path for p, eliminating . and .. elements.
856 func cleanPath(p string) string {
864 // path.Clean removes trailing slash except for root;
865 // put the trailing slash back if necessary.
866 if p[len(p)-1] == '/' && np != "/" {
872 // Find a handler on a handler map given a path string
873 // Most-specific (longest) pattern wins
874 func (mux *ServeMux) match(path string) Handler {
877 for k, v := range mux.m {
878 if !pathMatch(k, path) {
881 if h == nil || len(k) > n {
889 // ServeHTTP dispatches the request to the handler whose
890 // pattern most closely matches the request URL.
891 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
892 // Clean path to canonical form and redirect.
893 if p := cleanPath(r.URL.Path); p != r.URL.Path {
894 w.Header().Set("Location", p)
895 w.WriteHeader(StatusMovedPermanently)
898 // Host-specific pattern takes precedence over generic ones
899 h := mux.match(r.Host + r.URL.Path)
901 h = mux.match(r.URL.Path)
904 h = NotFoundHandler()
909 // Handle registers the handler for the given pattern.
910 func (mux *ServeMux) Handle(pattern string, handler Handler) {
912 panic("http: invalid pattern " + pattern)
915 mux.m[pattern] = handler
918 // If pattern is /tree/, insert permanent redirect for /tree.
920 if n > 0 && pattern[n-1] == '/' {
921 mux.m[pattern[0:n-1]] = RedirectHandler(pattern, StatusMovedPermanently)
925 // HandleFunc registers the handler function for the given pattern.
926 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
927 mux.Handle(pattern, HandlerFunc(handler))
930 // Handle registers the handler for the given pattern
931 // in the DefaultServeMux.
932 // The documentation for ServeMux explains how patterns are matched.
933 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
935 // HandleFunc registers the handler function for the given pattern
936 // in the DefaultServeMux.
937 // The documentation for ServeMux explains how patterns are matched.
938 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
939 DefaultServeMux.HandleFunc(pattern, handler)
942 // Serve accepts incoming HTTP connections on the listener l,
943 // creating a new service thread for each. The service threads
944 // read requests and then call handler to reply to them.
945 // Handler is typically nil, in which case the DefaultServeMux is used.
946 func Serve(l net.Listener, handler Handler) error {
947 srv := &Server{Handler: handler}
951 // A Server defines parameters for running an HTTP server.
953 Addr string // TCP address to listen on, ":http" if empty
954 Handler Handler // handler to invoke, http.DefaultServeMux if nil
955 ReadTimeout int64 // the net.Conn.SetReadTimeout value for new connections
956 WriteTimeout int64 // the net.Conn.SetWriteTimeout value for new connections
957 MaxHeaderBytes int // maximum size of request headers, DefaultMaxHeaderBytes if 0
960 // ListenAndServe listens on the TCP network address srv.Addr and then
961 // calls Serve to handle requests on incoming connections. If
962 // srv.Addr is blank, ":http" is used.
963 func (srv *Server) ListenAndServe() error {
968 l, e := net.Listen("tcp", addr)
975 // Serve accepts incoming connections on the Listener l, creating a
976 // new service thread for each. The service threads read requests and
977 // then call srv.Handler to reply to them.
978 func (srv *Server) Serve(l net.Listener) error {
983 if ne, ok := e.(net.Error); ok && ne.Temporary() {
984 log.Printf("http: Accept error: %v", e)
989 if srv.ReadTimeout != 0 {
990 rw.SetReadTimeout(srv.ReadTimeout)
992 if srv.WriteTimeout != 0 {
993 rw.SetWriteTimeout(srv.WriteTimeout)
995 c, err := srv.newConn(rw)
1001 panic("not reached")
1004 // ListenAndServe listens on the TCP network address addr
1005 // and then calls Serve with handler to handle requests
1006 // on incoming connections. Handler is typically nil,
1007 // in which case the DefaultServeMux is used.
1009 // A trivial example server is:
1019 // // hello world, the web server
1020 // func HelloServer(w http.ResponseWriter, req *http.Request) {
1021 // io.WriteString(w, "hello, world!\n")
1025 // http.HandleFunc("/hello", HelloServer)
1026 // err := http.ListenAndServe(":12345", nil)
1028 // log.Fatal("ListenAndServe: ", err.String())
1031 func ListenAndServe(addr string, handler Handler) error {
1032 server := &Server{Addr: addr, Handler: handler}
1033 return server.ListenAndServe()
1036 // ListenAndServeTLS acts identically to ListenAndServe, except that it
1037 // expects HTTPS connections. Additionally, files containing a certificate and
1038 // matching private key for the server must be provided. If the certificate
1039 // is signed by a certificate authority, the certFile should be the concatenation
1040 // of the server's certificate followed by the CA's certificate.
1042 // A trivial example server is:
1049 // func handler(w http.ResponseWriter, req *http.Request) {
1050 // w.Header().Set("Content-Type", "text/plain")
1051 // w.Write([]byte("This is an example server.\n"))
1055 // http.HandleFunc("/", handler)
1056 // log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
1057 // err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
1063 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
1064 func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
1065 server := &Server{Addr: addr, Handler: handler}
1066 return server.ListenAndServeTLS(certFile, keyFile)
1069 // ListenAndServeTLS listens on the TCP network address srv.Addr and
1070 // then calls Serve to handle requests on incoming TLS connections.
1072 // Filenames containing a certificate and matching private key for
1073 // the server must be provided. If the certificate is signed by a
1074 // certificate authority, the certFile should be the concatenation
1075 // of the server's certificate followed by the CA's certificate.
1077 // If srv.Addr is blank, ":https" is used.
1078 func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
1083 config := &tls.Config{
1086 NextProtos: []string{"http/1.1"},
1090 config.Certificates = make([]tls.Certificate, 1)
1091 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
1096 conn, err := net.Listen("tcp", addr)
1101 tlsListener := tls.NewListener(conn, config)
1102 return s.Serve(tlsListener)
1105 // TimeoutHandler returns a Handler that runs h with the given time limit.
1107 // The new Handler calls h.ServeHTTP to handle each request, but if a
1108 // call runs for more than ns nanoseconds, the handler responds with
1109 // a 503 Service Unavailable error and the given message in its body.
1110 // (If msg is empty, a suitable default message will be sent.)
1111 // After such a timeout, writes by h to its ResponseWriter will return
1112 // ErrHandlerTimeout.
1113 func TimeoutHandler(h Handler, ns int64, msg string) Handler {
1114 f := func() <-chan int64 {
1115 return time.After(ns)
1117 return &timeoutHandler{h, f, msg}
1120 // ErrHandlerTimeout is returned on ResponseWriter Write calls
1121 // in handlers which have timed out.
1122 var ErrHandlerTimeout = errors.New("http: Handler timeout")
1124 type timeoutHandler struct {
1126 timeout func() <-chan int64 // returns channel producing a timeout
1130 func (h *timeoutHandler) errorBody() string {
1134 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
1137 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
1138 done := make(chan bool)
1139 tw := &timeoutWriter{w: w}
1141 h.handler.ServeHTTP(tw, r)
1149 defer tw.mu.Unlock()
1150 if !tw.wroteHeader {
1151 tw.w.WriteHeader(StatusServiceUnavailable)
1152 tw.w.Write([]byte(h.errorBody()))
1158 type timeoutWriter struct {
1166 func (tw *timeoutWriter) Header() Header {
1167 return tw.w.Header()
1170 func (tw *timeoutWriter) Write(p []byte) (int, error) {
1172 timedOut := tw.timedOut
1175 return 0, ErrHandlerTimeout
1177 return tw.w.Write(p)
1180 func (tw *timeoutWriter) WriteHeader(code int) {
1182 if tw.timedOut || tw.wroteHeader {
1186 tw.wroteHeader = true
1188 tw.w.WriteHeader(code)