...
Run Format

Source file src/net/http/server.go

     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.
     4	
     5	// HTTP server.  See RFC 2616.
     6	
     7	package http
     8	
     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		"sync/atomic"
    26		"time"
    27	)
    28	
    29	// Errors introduced by the HTTP server.
    30	var (
    31		ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
    32		ErrBodyNotAllowed  = errors.New("http: request method or response status code does not allow body")
    33		ErrHijacked        = errors.New("Conn has been hijacked")
    34		ErrContentLength   = errors.New("Conn.Write wrote more than the declared Content-Length")
    35	)
    36	
    37	// Objects implementing the Handler interface can be
    38	// registered to serve a particular path or subtree
    39	// in the HTTP server.
    40	//
    41	// ServeHTTP should write reply headers and data to the ResponseWriter
    42	// and then return.  Returning signals that the request is finished
    43	// and that the HTTP server can move on to the next request on
    44	// the connection.
    45	//
    46	// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
    47	// that the effect of the panic was isolated to the active request.
    48	// It recovers the panic, logs a stack trace to the server error log,
    49	// and hangs up the connection.
    50	//
    51	type Handler interface {
    52		ServeHTTP(ResponseWriter, *Request)
    53	}
    54	
    55	// A ResponseWriter interface is used by an HTTP handler to
    56	// construct an HTTP response.
    57	type ResponseWriter interface {
    58		// Header returns the header map that will be sent by WriteHeader.
    59		// Changing the header after a call to WriteHeader (or Write) has
    60		// no effect.
    61		Header() Header
    62	
    63		// Write writes the data to the connection as part of an HTTP reply.
    64		// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
    65		// before writing the data.  If the Header does not contain a
    66		// Content-Type line, Write adds a Content-Type set to the result of passing
    67		// the initial 512 bytes of written data to DetectContentType.
    68		Write([]byte) (int, error)
    69	
    70		// WriteHeader sends an HTTP response header with status code.
    71		// If WriteHeader is not called explicitly, the first call to Write
    72		// will trigger an implicit WriteHeader(http.StatusOK).
    73		// Thus explicit calls to WriteHeader are mainly used to
    74		// send error codes.
    75		WriteHeader(int)
    76	}
    77	
    78	// The Flusher interface is implemented by ResponseWriters that allow
    79	// an HTTP handler to flush buffered data to the client.
    80	//
    81	// Note that even for ResponseWriters that support Flush,
    82	// if the client is connected through an HTTP proxy,
    83	// the buffered data may not reach the client until the response
    84	// completes.
    85	type Flusher interface {
    86		// Flush sends any buffered data to the client.
    87		Flush()
    88	}
    89	
    90	// The Hijacker interface is implemented by ResponseWriters that allow
    91	// an HTTP handler to take over the connection.
    92	type Hijacker interface {
    93		// Hijack lets the caller take over the connection.
    94		// After a call to Hijack(), the HTTP server library
    95		// will not do anything else with the connection.
    96		// It becomes the caller's responsibility to manage
    97		// and close the connection.
    98		Hijack() (net.Conn, *bufio.ReadWriter, error)
    99	}
   100	
   101	// The CloseNotifier interface is implemented by ResponseWriters which
   102	// allow detecting when the underlying connection has gone away.
   103	//
   104	// This mechanism can be used to cancel long operations on the server
   105	// if the client has disconnected before the response is ready.
   106	type CloseNotifier interface {
   107		// CloseNotify returns a channel that receives a single value
   108		// when the client connection has gone away.
   109		CloseNotify() <-chan bool
   110	}
   111	
   112	// A conn represents the server side of an HTTP connection.
   113	type conn struct {
   114		remoteAddr string               // network address of remote side
   115		server     *Server              // the Server on which the connection arrived
   116		rwc        net.Conn             // i/o connection
   117		w          io.Writer            // checkConnErrorWriter's copy of wrc, not zeroed on Hijack
   118		werr       error                // any errors writing to w
   119		sr         liveSwitchReader     // where the LimitReader reads from; usually the rwc
   120		lr         *io.LimitedReader    // io.LimitReader(sr)
   121		buf        *bufio.ReadWriter    // buffered(lr,rwc), reading from bufio->limitReader->sr->rwc
   122		tlsState   *tls.ConnectionState // or nil when not using TLS
   123	
   124		mu           sync.Mutex // guards the following
   125		clientGone   bool       // if client has disconnected mid-request
   126		closeNotifyc chan bool  // made lazily
   127		hijackedv    bool       // connection has been hijacked by handler
   128	}
   129	
   130	func (c *conn) hijacked() bool {
   131		c.mu.Lock()
   132		defer c.mu.Unlock()
   133		return c.hijackedv
   134	}
   135	
   136	func (c *conn) hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
   137		c.mu.Lock()
   138		defer c.mu.Unlock()
   139		if c.hijackedv {
   140			return nil, nil, ErrHijacked
   141		}
   142		if c.closeNotifyc != nil {
   143			return nil, nil, errors.New("http: Hijack is incompatible with use of CloseNotifier")
   144		}
   145		c.hijackedv = true
   146		rwc = c.rwc
   147		buf = c.buf
   148		c.rwc = nil
   149		c.buf = nil
   150		c.setState(rwc, StateHijacked)
   151		return
   152	}
   153	
   154	func (c *conn) closeNotify() <-chan bool {
   155		c.mu.Lock()
   156		defer c.mu.Unlock()
   157		if c.closeNotifyc == nil {
   158			c.closeNotifyc = make(chan bool, 1)
   159			if c.hijackedv {
   160				// to obey the function signature, even though
   161				// it'll never receive a value.
   162				return c.closeNotifyc
   163			}
   164			pr, pw := io.Pipe()
   165	
   166			readSource := c.sr.r
   167			c.sr.Lock()
   168			c.sr.r = pr
   169			c.sr.Unlock()
   170			go func() {
   171				_, err := io.Copy(pw, readSource)
   172				if err == nil {
   173					err = io.EOF
   174				}
   175				pw.CloseWithError(err)
   176				c.noteClientGone()
   177			}()
   178		}
   179		return c.closeNotifyc
   180	}
   181	
   182	func (c *conn) noteClientGone() {
   183		c.mu.Lock()
   184		defer c.mu.Unlock()
   185		if c.closeNotifyc != nil && !c.clientGone {
   186			c.closeNotifyc <- true
   187		}
   188		c.clientGone = true
   189	}
   190	
   191	// A switchReader can have its Reader changed at runtime.
   192	// It's not safe for concurrent Reads and switches.
   193	type switchReader struct {
   194		io.Reader
   195	}
   196	
   197	// A switchWriter can have its Writer changed at runtime.
   198	// It's not safe for concurrent Writes and switches.
   199	type switchWriter struct {
   200		io.Writer
   201	}
   202	
   203	// A liveSwitchReader is a switchReader that's safe for concurrent
   204	// reads and switches, if its mutex is held.
   205	type liveSwitchReader struct {
   206		sync.Mutex
   207		r io.Reader
   208	}
   209	
   210	func (sr *liveSwitchReader) Read(p []byte) (n int, err error) {
   211		sr.Lock()
   212		r := sr.r
   213		sr.Unlock()
   214		return r.Read(p)
   215	}
   216	
   217	// This should be >= 512 bytes for DetectContentType,
   218	// but otherwise it's somewhat arbitrary.
   219	const bufferBeforeChunkingSize = 2048
   220	
   221	// chunkWriter writes to a response's conn buffer, and is the writer
   222	// wrapped by the response.bufw buffered writer.
   223	//
   224	// chunkWriter also is responsible for finalizing the Header, including
   225	// conditionally setting the Content-Type and setting a Content-Length
   226	// in cases where the handler's final output is smaller than the buffer
   227	// size. It also conditionally adds chunk headers, when in chunking mode.
   228	//
   229	// See the comment above (*response).Write for the entire write flow.
   230	type chunkWriter struct {
   231		res *response
   232	
   233		// header is either nil or a deep clone of res.handlerHeader
   234		// at the time of res.WriteHeader, if res.WriteHeader is
   235		// called and extra buffering is being done to calculate
   236		// Content-Type and/or Content-Length.
   237		header Header
   238	
   239		// wroteHeader tells whether the header's been written to "the
   240		// wire" (or rather: w.conn.buf). this is unlike
   241		// (*response).wroteHeader, which tells only whether it was
   242		// logically written.
   243		wroteHeader bool
   244	
   245		// set by the writeHeader method:
   246		chunking bool // using chunked transfer encoding for reply body
   247	}
   248	
   249	var (
   250		crlf       = []byte("\r\n")
   251		colonSpace = []byte(": ")
   252	)
   253	
   254	func (cw *chunkWriter) Write(p []byte) (n int, err error) {
   255		if !cw.wroteHeader {
   256			cw.writeHeader(p)
   257		}
   258		if cw.res.req.Method == "HEAD" {
   259			// Eat writes.
   260			return len(p), nil
   261		}
   262		if cw.chunking {
   263			_, err = fmt.Fprintf(cw.res.conn.buf, "%x\r\n", len(p))
   264			if err != nil {
   265				cw.res.conn.rwc.Close()
   266				return
   267			}
   268		}
   269		n, err = cw.res.conn.buf.Write(p)
   270		if cw.chunking && err == nil {
   271			_, err = cw.res.conn.buf.Write(crlf)
   272		}
   273		if err != nil {
   274			cw.res.conn.rwc.Close()
   275		}
   276		return
   277	}
   278	
   279	func (cw *chunkWriter) flush() {
   280		if !cw.wroteHeader {
   281			cw.writeHeader(nil)
   282		}
   283		cw.res.conn.buf.Flush()
   284	}
   285	
   286	func (cw *chunkWriter) close() {
   287		if !cw.wroteHeader {
   288			cw.writeHeader(nil)
   289		}
   290		if cw.chunking {
   291			// zero EOF chunk, trailer key/value pairs (currently
   292			// unsupported in Go's server), followed by a blank
   293			// line.
   294			cw.res.conn.buf.WriteString("0\r\n\r\n")
   295		}
   296	}
   297	
   298	// A response represents the server side of an HTTP response.
   299	type response struct {
   300		conn          *conn
   301		req           *Request // request for this response
   302		wroteHeader   bool     // reply header has been (logically) written
   303		wroteContinue bool     // 100 Continue response was written
   304	
   305		w  *bufio.Writer // buffers output in chunks to chunkWriter
   306		cw chunkWriter
   307		sw *switchWriter // of the bufio.Writer, for return to putBufioWriter
   308	
   309		// handlerHeader is the Header that Handlers get access to,
   310		// which may be retained and mutated even after WriteHeader.
   311		// handlerHeader is copied into cw.header at WriteHeader
   312		// time, and privately mutated thereafter.
   313		handlerHeader Header
   314		calledHeader  bool // handler accessed handlerHeader via Header
   315	
   316		written       int64 // number of bytes written in body
   317		contentLength int64 // explicitly-declared Content-Length; or -1
   318		status        int   // status code passed to WriteHeader
   319	
   320		// close connection after this reply.  set on request and
   321		// updated after response from handler if there's a
   322		// "Connection: keep-alive" response header and a
   323		// Content-Length.
   324		closeAfterReply bool
   325	
   326		// requestBodyLimitHit is set by requestTooLarge when
   327		// maxBytesReader hits its max size. It is checked in
   328		// WriteHeader, to make sure we don't consume the
   329		// remaining request body to try to advance to the next HTTP
   330		// request. Instead, when this is set, we stop reading
   331		// subsequent requests on this connection and stop reading
   332		// input from it.
   333		requestBodyLimitHit bool
   334	
   335		handlerDone bool // set true when the handler exits
   336	
   337		// Buffers for Date and Content-Length
   338		dateBuf [len(TimeFormat)]byte
   339		clenBuf [10]byte
   340	}
   341	
   342	// requestTooLarge is called by maxBytesReader when too much input has
   343	// been read from the client.
   344	func (w *response) requestTooLarge() {
   345		w.closeAfterReply = true
   346		w.requestBodyLimitHit = true
   347		if !w.wroteHeader {
   348			w.Header().Set("Connection", "close")
   349		}
   350	}
   351	
   352	// needsSniff reports whether a Content-Type still needs to be sniffed.
   353	func (w *response) needsSniff() bool {
   354		_, haveType := w.handlerHeader["Content-Type"]
   355		return !w.cw.wroteHeader && !haveType && w.written < sniffLen
   356	}
   357	
   358	// writerOnly hides an io.Writer value's optional ReadFrom method
   359	// from io.Copy.
   360	type writerOnly struct {
   361		io.Writer
   362	}
   363	
   364	func srcIsRegularFile(src io.Reader) (isRegular bool, err error) {
   365		switch v := src.(type) {
   366		case *os.File:
   367			fi, err := v.Stat()
   368			if err != nil {
   369				return false, err
   370			}
   371			return fi.Mode().IsRegular(), nil
   372		case *io.LimitedReader:
   373			return srcIsRegularFile(v.R)
   374		default:
   375			return
   376		}
   377	}
   378	
   379	// ReadFrom is here to optimize copying from an *os.File regular file
   380	// to a *net.TCPConn with sendfile.
   381	func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
   382		// Our underlying w.conn.rwc is usually a *TCPConn (with its
   383		// own ReadFrom method). If not, or if our src isn't a regular
   384		// file, just fall back to the normal copy method.
   385		rf, ok := w.conn.rwc.(io.ReaderFrom)
   386		regFile, err := srcIsRegularFile(src)
   387		if err != nil {
   388			return 0, err
   389		}
   390		if !ok || !regFile {
   391			return io.Copy(writerOnly{w}, src)
   392		}
   393	
   394		// sendfile path:
   395	
   396		if !w.wroteHeader {
   397			w.WriteHeader(StatusOK)
   398		}
   399	
   400		if w.needsSniff() {
   401			n0, err := io.Copy(writerOnly{w}, io.LimitReader(src, sniffLen))
   402			n += n0
   403			if err != nil {
   404				return n, err
   405			}
   406		}
   407	
   408		w.w.Flush()  // get rid of any previous writes
   409		w.cw.flush() // make sure Header is written; flush data to rwc
   410	
   411		// Now that cw has been flushed, its chunking field is guaranteed initialized.
   412		if !w.cw.chunking && w.bodyAllowed() {
   413			n0, err := rf.ReadFrom(src)
   414			n += n0
   415			w.written += n0
   416			return n, err
   417		}
   418	
   419		n0, err := io.Copy(writerOnly{w}, src)
   420		n += n0
   421		return n, err
   422	}
   423	
   424	// noLimit is an effective infinite upper bound for io.LimitedReader
   425	const noLimit int64 = (1 << 63) - 1
   426	
   427	// debugServerConnections controls whether all server connections are wrapped
   428	// with a verbose logging wrapper.
   429	const debugServerConnections = false
   430	
   431	// Create new connection from rwc.
   432	func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
   433		c = new(conn)
   434		c.remoteAddr = rwc.RemoteAddr().String()
   435		c.server = srv
   436		c.rwc = rwc
   437		c.w = rwc
   438		if debugServerConnections {
   439			c.rwc = newLoggingConn("server", c.rwc)
   440		}
   441		c.sr = liveSwitchReader{r: c.rwc}
   442		c.lr = io.LimitReader(&c.sr, noLimit).(*io.LimitedReader)
   443		br := newBufioReader(c.lr)
   444		bw := newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
   445		c.buf = bufio.NewReadWriter(br, bw)
   446		return c, nil
   447	}
   448	
   449	var (
   450		bufioReaderPool   sync.Pool
   451		bufioWriter2kPool sync.Pool
   452		bufioWriter4kPool sync.Pool
   453	)
   454	
   455	func bufioWriterPool(size int) *sync.Pool {
   456		switch size {
   457		case 2 << 10:
   458			return &bufioWriter2kPool
   459		case 4 << 10:
   460			return &bufioWriter4kPool
   461		}
   462		return nil
   463	}
   464	
   465	func newBufioReader(r io.Reader) *bufio.Reader {
   466		if v := bufioReaderPool.Get(); v != nil {
   467			br := v.(*bufio.Reader)
   468			br.Reset(r)
   469			return br
   470		}
   471		return bufio.NewReader(r)
   472	}
   473	
   474	func putBufioReader(br *bufio.Reader) {
   475		br.Reset(nil)
   476		bufioReaderPool.Put(br)
   477	}
   478	
   479	func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
   480		pool := bufioWriterPool(size)
   481		if pool != nil {
   482			if v := pool.Get(); v != nil {
   483				bw := v.(*bufio.Writer)
   484				bw.Reset(w)
   485				return bw
   486			}
   487		}
   488		return bufio.NewWriterSize(w, size)
   489	}
   490	
   491	func putBufioWriter(bw *bufio.Writer) {
   492		bw.Reset(nil)
   493		if pool := bufioWriterPool(bw.Available()); pool != nil {
   494			pool.Put(bw)
   495		}
   496	}
   497	
   498	// DefaultMaxHeaderBytes is the maximum permitted size of the headers
   499	// in an HTTP request.
   500	// This can be overridden by setting Server.MaxHeaderBytes.
   501	const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
   502	
   503	func (srv *Server) maxHeaderBytes() int {
   504		if srv.MaxHeaderBytes > 0 {
   505			return srv.MaxHeaderBytes
   506		}
   507		return DefaultMaxHeaderBytes
   508	}
   509	
   510	func (srv *Server) initialLimitedReaderSize() int64 {
   511		return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
   512	}
   513	
   514	// wrapper around io.ReaderCloser which on first read, sends an
   515	// HTTP/1.1 100 Continue header
   516	type expectContinueReader struct {
   517		resp       *response
   518		readCloser io.ReadCloser
   519		closed     bool
   520	}
   521	
   522	func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
   523		if ecr.closed {
   524			return 0, ErrBodyReadAfterClose
   525		}
   526		if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked() {
   527			ecr.resp.wroteContinue = true
   528			ecr.resp.conn.buf.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
   529			ecr.resp.conn.buf.Flush()
   530		}
   531		return ecr.readCloser.Read(p)
   532	}
   533	
   534	func (ecr *expectContinueReader) Close() error {
   535		ecr.closed = true
   536		return ecr.readCloser.Close()
   537	}
   538	
   539	// TimeFormat is the time format to use with
   540	// time.Parse and time.Time.Format when parsing
   541	// or generating times in HTTP headers.
   542	// It is like time.RFC1123 but hard codes GMT as the time zone.
   543	const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
   544	
   545	// appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
   546	func appendTime(b []byte, t time.Time) []byte {
   547		const days = "SunMonTueWedThuFriSat"
   548		const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
   549	
   550		t = t.UTC()
   551		yy, mm, dd := t.Date()
   552		hh, mn, ss := t.Clock()
   553		day := days[3*t.Weekday():]
   554		mon := months[3*(mm-1):]
   555	
   556		return append(b,
   557			day[0], day[1], day[2], ',', ' ',
   558			byte('0'+dd/10), byte('0'+dd%10), ' ',
   559			mon[0], mon[1], mon[2], ' ',
   560			byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
   561			byte('0'+hh/10), byte('0'+hh%10), ':',
   562			byte('0'+mn/10), byte('0'+mn%10), ':',
   563			byte('0'+ss/10), byte('0'+ss%10), ' ',
   564			'G', 'M', 'T')
   565	}
   566	
   567	var errTooLarge = errors.New("http: request too large")
   568	
   569	// Read next request from connection.
   570	func (c *conn) readRequest() (w *response, err error) {
   571		if c.hijacked() {
   572			return nil, ErrHijacked
   573		}
   574	
   575		if d := c.server.ReadTimeout; d != 0 {
   576			c.rwc.SetReadDeadline(time.Now().Add(d))
   577		}
   578		if d := c.server.WriteTimeout; d != 0 {
   579			defer func() {
   580				c.rwc.SetWriteDeadline(time.Now().Add(d))
   581			}()
   582		}
   583	
   584		c.lr.N = c.server.initialLimitedReaderSize()
   585		var req *Request
   586		if req, err = ReadRequest(c.buf.Reader); err != nil {
   587			if c.lr.N == 0 {
   588				return nil, errTooLarge
   589			}
   590			return nil, err
   591		}
   592		c.lr.N = noLimit
   593	
   594		req.RemoteAddr = c.remoteAddr
   595		req.TLS = c.tlsState
   596	
   597		w = &response{
   598			conn:          c,
   599			req:           req,
   600			handlerHeader: make(Header),
   601			contentLength: -1,
   602		}
   603		w.cw.res = w
   604		w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
   605		return w, nil
   606	}
   607	
   608	func (w *response) Header() Header {
   609		if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
   610			// Accessing the header between logically writing it
   611			// and physically writing it means we need to allocate
   612			// a clone to snapshot the logically written state.
   613			w.cw.header = w.handlerHeader.clone()
   614		}
   615		w.calledHeader = true
   616		return w.handlerHeader
   617	}
   618	
   619	// maxPostHandlerReadBytes is the max number of Request.Body bytes not
   620	// consumed by a handler that the server will read from the client
   621	// in order to keep a connection alive.  If there are more bytes than
   622	// this then the server to be paranoid instead sends a "Connection:
   623	// close" response.
   624	//
   625	// This number is approximately what a typical machine's TCP buffer
   626	// size is anyway.  (if we have the bytes on the machine, we might as
   627	// well read them)
   628	const maxPostHandlerReadBytes = 256 << 10
   629	
   630	func (w *response) WriteHeader(code int) {
   631		if w.conn.hijacked() {
   632			w.conn.server.logf("http: response.WriteHeader on hijacked connection")
   633			return
   634		}
   635		if w.wroteHeader {
   636			w.conn.server.logf("http: multiple response.WriteHeader calls")
   637			return
   638		}
   639		w.wroteHeader = true
   640		w.status = code
   641	
   642		if w.calledHeader && w.cw.header == nil {
   643			w.cw.header = w.handlerHeader.clone()
   644		}
   645	
   646		if cl := w.handlerHeader.get("Content-Length"); cl != "" {
   647			v, err := strconv.ParseInt(cl, 10, 64)
   648			if err == nil && v >= 0 {
   649				w.contentLength = v
   650			} else {
   651				w.conn.server.logf("http: invalid Content-Length of %q", cl)
   652				w.handlerHeader.Del("Content-Length")
   653			}
   654		}
   655	}
   656	
   657	// extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
   658	// This type is used to avoid extra allocations from cloning and/or populating
   659	// the response Header map and all its 1-element slices.
   660	type extraHeader struct {
   661		contentType      string
   662		connection       string
   663		transferEncoding string
   664		date             []byte // written if not nil
   665		contentLength    []byte // written if not nil
   666	}
   667	
   668	// Sorted the same as extraHeader.Write's loop.
   669	var extraHeaderKeys = [][]byte{
   670		[]byte("Content-Type"),
   671		[]byte("Connection"),
   672		[]byte("Transfer-Encoding"),
   673	}
   674	
   675	var (
   676		headerContentLength = []byte("Content-Length: ")
   677		headerDate          = []byte("Date: ")
   678	)
   679	
   680	// Write writes the headers described in h to w.
   681	//
   682	// This method has a value receiver, despite the somewhat large size
   683	// of h, because it prevents an allocation. The escape analysis isn't
   684	// smart enough to realize this function doesn't mutate h.
   685	func (h extraHeader) Write(w *bufio.Writer) {
   686		if h.date != nil {
   687			w.Write(headerDate)
   688			w.Write(h.date)
   689			w.Write(crlf)
   690		}
   691		if h.contentLength != nil {
   692			w.Write(headerContentLength)
   693			w.Write(h.contentLength)
   694			w.Write(crlf)
   695		}
   696		for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
   697			if v != "" {
   698				w.Write(extraHeaderKeys[i])
   699				w.Write(colonSpace)
   700				w.WriteString(v)
   701				w.Write(crlf)
   702			}
   703		}
   704	}
   705	
   706	// writeHeader finalizes the header sent to the client and writes it
   707	// to cw.res.conn.buf.
   708	//
   709	// p is not written by writeHeader, but is the first chunk of the body
   710	// that will be written.  It is sniffed for a Content-Type if none is
   711	// set explicitly.  It's also used to set the Content-Length, if the
   712	// total body size was small and the handler has already finished
   713	// running.
   714	func (cw *chunkWriter) writeHeader(p []byte) {
   715		if cw.wroteHeader {
   716			return
   717		}
   718		cw.wroteHeader = true
   719	
   720		w := cw.res
   721		keepAlivesEnabled := w.conn.server.doKeepAlives()
   722		isHEAD := w.req.Method == "HEAD"
   723	
   724		// header is written out to w.conn.buf below. Depending on the
   725		// state of the handler, we either own the map or not. If we
   726		// don't own it, the exclude map is created lazily for
   727		// WriteSubset to remove headers. The setHeader struct holds
   728		// headers we need to add.
   729		header := cw.header
   730		owned := header != nil
   731		if !owned {
   732			header = w.handlerHeader
   733		}
   734		var excludeHeader map[string]bool
   735		delHeader := func(key string) {
   736			if owned {
   737				header.Del(key)
   738				return
   739			}
   740			if _, ok := header[key]; !ok {
   741				return
   742			}
   743			if excludeHeader == nil {
   744				excludeHeader = make(map[string]bool)
   745			}
   746			excludeHeader[key] = true
   747		}
   748		var setHeader extraHeader
   749	
   750		// If the handler is done but never sent a Content-Length
   751		// response header and this is our first (and last) write, set
   752		// it, even to zero. This helps HTTP/1.0 clients keep their
   753		// "keep-alive" connections alive.
   754		// Exceptions: 304/204/1xx responses never get Content-Length, and if
   755		// it was a HEAD request, we don't know the difference between
   756		// 0 actual bytes and 0 bytes because the handler noticed it
   757		// was a HEAD request and chose not to write anything.  So for
   758		// HEAD, the handler should either write the Content-Length or
   759		// write non-zero bytes.  If it's actually 0 bytes and the
   760		// handler never looked at the Request.Method, we just don't
   761		// send a Content-Length header.
   762		if w.handlerDone && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
   763			w.contentLength = int64(len(p))
   764			setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
   765		}
   766	
   767		// If this was an HTTP/1.0 request with keep-alive and we sent a
   768		// Content-Length back, we can make this a keep-alive response ...
   769		if w.req.wantsHttp10KeepAlive() && keepAlivesEnabled {
   770			sentLength := header.get("Content-Length") != ""
   771			if sentLength && header.get("Connection") == "keep-alive" {
   772				w.closeAfterReply = false
   773			}
   774		}
   775	
   776		// Check for a explicit (and valid) Content-Length header.
   777		hasCL := w.contentLength != -1
   778	
   779		if w.req.wantsHttp10KeepAlive() && (isHEAD || hasCL) {
   780			_, connectionHeaderSet := header["Connection"]
   781			if !connectionHeaderSet {
   782				setHeader.connection = "keep-alive"
   783			}
   784		} else if !w.req.ProtoAtLeast(1, 1) || w.req.wantsClose() {
   785			w.closeAfterReply = true
   786		}
   787	
   788		if header.get("Connection") == "close" || !keepAlivesEnabled {
   789			w.closeAfterReply = true
   790		}
   791	
   792		// Per RFC 2616, we should consume the request body before
   793		// replying, if the handler hasn't already done so.  But we
   794		// don't want to do an unbounded amount of reading here for
   795		// DoS reasons, so we only try up to a threshold.
   796		if w.req.ContentLength != 0 && !w.closeAfterReply {
   797			ecr, isExpecter := w.req.Body.(*expectContinueReader)
   798			if !isExpecter || ecr.resp.wroteContinue {
   799				n, _ := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1)
   800				if n >= maxPostHandlerReadBytes {
   801					w.requestTooLarge()
   802					delHeader("Connection")
   803					setHeader.connection = "close"
   804				} else {
   805					w.req.Body.Close()
   806				}
   807			}
   808		}
   809	
   810		code := w.status
   811		if bodyAllowedForStatus(code) {
   812			// If no content type, apply sniffing algorithm to body.
   813			_, haveType := header["Content-Type"]
   814			if !haveType {
   815				setHeader.contentType = DetectContentType(p)
   816			}
   817		} else {
   818			for _, k := range suppressedHeaders(code) {
   819				delHeader(k)
   820			}
   821		}
   822	
   823		if _, ok := header["Date"]; !ok {
   824			setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
   825		}
   826	
   827		te := header.get("Transfer-Encoding")
   828		hasTE := te != ""
   829		if hasCL && hasTE && te != "identity" {
   830			// TODO: return an error if WriteHeader gets a return parameter
   831			// For now just ignore the Content-Length.
   832			w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
   833				te, w.contentLength)
   834			delHeader("Content-Length")
   835			hasCL = false
   836		}
   837	
   838		if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) {
   839			// do nothing
   840		} else if code == StatusNoContent {
   841			delHeader("Transfer-Encoding")
   842		} else if hasCL {
   843			delHeader("Transfer-Encoding")
   844		} else if w.req.ProtoAtLeast(1, 1) {
   845			// HTTP/1.1 or greater: Transfer-Encoding has been set to identity,  and no
   846			// content-length has been provided. The connection must be closed after the
   847			// reply is written, and no chunking is to be done. This is the setup
   848			// recommended in the Server-Sent Events candidate recommendation 11,
   849			// section 8.
   850			if hasTE && te == "identity" {
   851				cw.chunking = false
   852				w.closeAfterReply = true
   853			} else {
   854				// HTTP/1.1 or greater: use chunked transfer encoding
   855				// to avoid closing the connection at EOF.
   856				cw.chunking = true
   857				setHeader.transferEncoding = "chunked"
   858			}
   859		} else {
   860			// HTTP version < 1.1: cannot do chunked transfer
   861			// encoding and we don't know the Content-Length so
   862			// signal EOF by closing connection.
   863			w.closeAfterReply = true
   864			delHeader("Transfer-Encoding") // in case already set
   865		}
   866	
   867		// Cannot use Content-Length with non-identity Transfer-Encoding.
   868		if cw.chunking {
   869			delHeader("Content-Length")
   870		}
   871		if !w.req.ProtoAtLeast(1, 0) {
   872			return
   873		}
   874	
   875		if w.closeAfterReply && (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) {
   876			delHeader("Connection")
   877			if w.req.ProtoAtLeast(1, 1) {
   878				setHeader.connection = "close"
   879			}
   880		}
   881	
   882		w.conn.buf.WriteString(statusLine(w.req, code))
   883		cw.header.WriteSubset(w.conn.buf, excludeHeader)
   884		setHeader.Write(w.conn.buf.Writer)
   885		w.conn.buf.Write(crlf)
   886	}
   887	
   888	// statusLines is a cache of Status-Line strings, keyed by code (for
   889	// HTTP/1.1) or negative code (for HTTP/1.0). This is faster than a
   890	// map keyed by struct of two fields. This map's max size is bounded
   891	// by 2*len(statusText), two protocol types for each known official
   892	// status code in the statusText map.
   893	var (
   894		statusMu    sync.RWMutex
   895		statusLines = make(map[int]string)
   896	)
   897	
   898	// statusLine returns a response Status-Line (RFC 2616 Section 6.1)
   899	// for the given request and response status code.
   900	func statusLine(req *Request, code int) string {
   901		// Fast path:
   902		key := code
   903		proto11 := req.ProtoAtLeast(1, 1)
   904		if !proto11 {
   905			key = -key
   906		}
   907		statusMu.RLock()
   908		line, ok := statusLines[key]
   909		statusMu.RUnlock()
   910		if ok {
   911			return line
   912		}
   913	
   914		// Slow path:
   915		proto := "HTTP/1.0"
   916		if proto11 {
   917			proto = "HTTP/1.1"
   918		}
   919		codestring := strconv.Itoa(code)
   920		text, ok := statusText[code]
   921		if !ok {
   922			text = "status code " + codestring
   923		}
   924		line = proto + " " + codestring + " " + text + "\r\n"
   925		if ok {
   926			statusMu.Lock()
   927			defer statusMu.Unlock()
   928			statusLines[key] = line
   929		}
   930		return line
   931	}
   932	
   933	// bodyAllowed returns true if a Write is allowed for this response type.
   934	// It's illegal to call this before the header has been flushed.
   935	func (w *response) bodyAllowed() bool {
   936		if !w.wroteHeader {
   937			panic("")
   938		}
   939		return bodyAllowedForStatus(w.status)
   940	}
   941	
   942	// The Life Of A Write is like this:
   943	//
   944	// Handler starts. No header has been sent. The handler can either
   945	// write a header, or just start writing.  Writing before sending a header
   946	// sends an implicitly empty 200 OK header.
   947	//
   948	// If the handler didn't declare a Content-Length up front, we either
   949	// go into chunking mode or, if the handler finishes running before
   950	// the chunking buffer size, we compute a Content-Length and send that
   951	// in the header instead.
   952	//
   953	// Likewise, if the handler didn't set a Content-Type, we sniff that
   954	// from the initial chunk of output.
   955	//
   956	// The Writers are wired together like:
   957	//
   958	// 1. *response (the ResponseWriter) ->
   959	// 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
   960	// 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
   961	//    and which writes the chunk headers, if needed.
   962	// 4. conn.buf, a bufio.Writer of default (4kB) bytes, writing to ->
   963	// 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
   964	//    and populates c.werr with it if so. but otherwise writes to:
   965	// 6. the rwc, the net.Conn.
   966	//
   967	// TODO(bradfitz): short-circuit some of the buffering when the
   968	// initial header contains both a Content-Type and Content-Length.
   969	// Also short-circuit in (1) when the header's been sent and not in
   970	// chunking mode, writing directly to (4) instead, if (2) has no
   971	// buffered data.  More generally, we could short-circuit from (1) to
   972	// (3) even in chunking mode if the write size from (1) is over some
   973	// threshold and nothing is in (2).  The answer might be mostly making
   974	// bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
   975	// with this instead.
   976	func (w *response) Write(data []byte) (n int, err error) {
   977		return w.write(len(data), data, "")
   978	}
   979	
   980	func (w *response) WriteString(data string) (n int, err error) {
   981		return w.write(len(data), nil, data)
   982	}
   983	
   984	// either dataB or dataS is non-zero.
   985	func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
   986		if w.conn.hijacked() {
   987			w.conn.server.logf("http: response.Write on hijacked connection")
   988			return 0, ErrHijacked
   989		}
   990		if !w.wroteHeader {
   991			w.WriteHeader(StatusOK)
   992		}
   993		if lenData == 0 {
   994			return 0, nil
   995		}
   996		if !w.bodyAllowed() {
   997			return 0, ErrBodyNotAllowed
   998		}
   999	
  1000		w.written += int64(lenData) // ignoring errors, for errorKludge
  1001		if w.contentLength != -1 && w.written > w.contentLength {
  1002			return 0, ErrContentLength
  1003		}
  1004		if dataB != nil {
  1005			return w.w.Write(dataB)
  1006		} else {
  1007			return w.w.WriteString(dataS)
  1008		}
  1009	}
  1010	
  1011	func (w *response) finishRequest() {
  1012		w.handlerDone = true
  1013	
  1014		if !w.wroteHeader {
  1015			w.WriteHeader(StatusOK)
  1016		}
  1017	
  1018		w.w.Flush()
  1019		putBufioWriter(w.w)
  1020		w.cw.close()
  1021		w.conn.buf.Flush()
  1022	
  1023		// Close the body (regardless of w.closeAfterReply) so we can
  1024		// re-use its bufio.Reader later safely.
  1025		w.req.Body.Close()
  1026	
  1027		if w.req.MultipartForm != nil {
  1028			w.req.MultipartForm.RemoveAll()
  1029		}
  1030	
  1031		if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
  1032			// Did not write enough. Avoid getting out of sync.
  1033			w.closeAfterReply = true
  1034		}
  1035	
  1036		// There was some error writing to the underlying connection
  1037		// during the request, so don't re-use this conn.
  1038		if w.conn.werr != nil {
  1039			w.closeAfterReply = true
  1040		}
  1041	}
  1042	
  1043	func (w *response) Flush() {
  1044		if !w.wroteHeader {
  1045			w.WriteHeader(StatusOK)
  1046		}
  1047		w.w.Flush()
  1048		w.cw.flush()
  1049	}
  1050	
  1051	func (c *conn) finalFlush() {
  1052		if c.buf != nil {
  1053			c.buf.Flush()
  1054	
  1055			// Steal the bufio.Reader (~4KB worth of memory) and its associated
  1056			// reader for a future connection.
  1057			putBufioReader(c.buf.Reader)
  1058	
  1059			// Steal the bufio.Writer (~4KB worth of memory) and its associated
  1060			// writer for a future connection.
  1061			putBufioWriter(c.buf.Writer)
  1062	
  1063			c.buf = nil
  1064		}
  1065	}
  1066	
  1067	// Close the connection.
  1068	func (c *conn) close() {
  1069		c.finalFlush()
  1070		if c.rwc != nil {
  1071			c.rwc.Close()
  1072			c.rwc = nil
  1073		}
  1074	}
  1075	
  1076	// rstAvoidanceDelay is the amount of time we sleep after closing the
  1077	// write side of a TCP connection before closing the entire socket.
  1078	// By sleeping, we increase the chances that the client sees our FIN
  1079	// and processes its final data before they process the subsequent RST
  1080	// from closing a connection with known unread data.
  1081	// This RST seems to occur mostly on BSD systems. (And Windows?)
  1082	// This timeout is somewhat arbitrary (~latency around the planet).
  1083	const rstAvoidanceDelay = 500 * time.Millisecond
  1084	
  1085	type closeWriter interface {
  1086		CloseWrite() error
  1087	}
  1088	
  1089	var _ closeWriter = (*net.TCPConn)(nil)
  1090	
  1091	// closeWrite flushes any outstanding data and sends a FIN packet (if
  1092	// client is connected via TCP), signalling that we're done.  We then
  1093	// pause for a bit, hoping the client processes it before any
  1094	// subsequent RST.
  1095	//
  1096	// See http://golang.org/issue/3595
  1097	func (c *conn) closeWriteAndWait() {
  1098		c.finalFlush()
  1099		if tcp, ok := c.rwc.(closeWriter); ok {
  1100			tcp.CloseWrite()
  1101		}
  1102		time.Sleep(rstAvoidanceDelay)
  1103	}
  1104	
  1105	// validNPN reports whether the proto is not a blacklisted Next
  1106	// Protocol Negotiation protocol.  Empty and built-in protocol types
  1107	// are blacklisted and can't be overridden with alternate
  1108	// implementations.
  1109	func validNPN(proto string) bool {
  1110		switch proto {
  1111		case "", "http/1.1", "http/1.0":
  1112			return false
  1113		}
  1114		return true
  1115	}
  1116	
  1117	func (c *conn) setState(nc net.Conn, state ConnState) {
  1118		if hook := c.server.ConnState; hook != nil {
  1119			hook(nc, state)
  1120		}
  1121	}
  1122	
  1123	// Serve a new connection.
  1124	func (c *conn) serve() {
  1125		origConn := c.rwc // copy it before it's set nil on Close or Hijack
  1126		defer func() {
  1127			if err := recover(); err != nil {
  1128				const size = 64 << 10
  1129				buf := make([]byte, size)
  1130				buf = buf[:runtime.Stack(buf, false)]
  1131				c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
  1132			}
  1133			if !c.hijacked() {
  1134				c.close()
  1135				c.setState(origConn, StateClosed)
  1136			}
  1137		}()
  1138	
  1139		if tlsConn, ok := c.rwc.(*tls.Conn); ok {
  1140			if d := c.server.ReadTimeout; d != 0 {
  1141				c.rwc.SetReadDeadline(time.Now().Add(d))
  1142			}
  1143			if d := c.server.WriteTimeout; d != 0 {
  1144				c.rwc.SetWriteDeadline(time.Now().Add(d))
  1145			}
  1146			if err := tlsConn.Handshake(); err != nil {
  1147				c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
  1148				return
  1149			}
  1150			c.tlsState = new(tls.ConnectionState)
  1151			*c.tlsState = tlsConn.ConnectionState()
  1152			if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
  1153				if fn := c.server.TLSNextProto[proto]; fn != nil {
  1154					h := initNPNRequest{tlsConn, serverHandler{c.server}}
  1155					fn(c.server, tlsConn, h)
  1156				}
  1157				return
  1158			}
  1159		}
  1160	
  1161		for {
  1162			w, err := c.readRequest()
  1163			if c.lr.N != c.server.initialLimitedReaderSize() {
  1164				// If we read any bytes off the wire, we're active.
  1165				c.setState(c.rwc, StateActive)
  1166			}
  1167			if err != nil {
  1168				if err == errTooLarge {
  1169					// Their HTTP client may or may not be
  1170					// able to read this if we're
  1171					// responding to them and hanging up
  1172					// while they're still writing their
  1173					// request.  Undefined behavior.
  1174					io.WriteString(c.rwc, "HTTP/1.1 413 Request Entity Too Large\r\n\r\n")
  1175					c.closeWriteAndWait()
  1176					break
  1177				} else if err == io.EOF {
  1178					break // Don't reply
  1179				} else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  1180					break // Don't reply
  1181				}
  1182				io.WriteString(c.rwc, "HTTP/1.1 400 Bad Request\r\n\r\n")
  1183				break
  1184			}
  1185	
  1186			// Expect 100 Continue support
  1187			req := w.req
  1188			if req.expectsContinue() {
  1189				if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
  1190					// Wrap the Body reader with one that replies on the connection
  1191					req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
  1192				}
  1193				req.Header.Del("Expect")
  1194			} else if req.Header.get("Expect") != "" {
  1195				w.sendExpectationFailed()
  1196				break
  1197			}
  1198	
  1199			// HTTP cannot have multiple simultaneous active requests.[*]
  1200			// Until the server replies to this request, it can't read another,
  1201			// so we might as well run the handler in this goroutine.
  1202			// [*] Not strictly true: HTTP pipelining.  We could let them all process
  1203			// in parallel even if their responses need to be serialized.
  1204			serverHandler{c.server}.ServeHTTP(w, w.req)
  1205			if c.hijacked() {
  1206				return
  1207			}
  1208			w.finishRequest()
  1209			if w.closeAfterReply {
  1210				if w.requestBodyLimitHit {
  1211					c.closeWriteAndWait()
  1212				}
  1213				break
  1214			}
  1215			c.setState(c.rwc, StateIdle)
  1216		}
  1217	}
  1218	
  1219	func (w *response) sendExpectationFailed() {
  1220		// TODO(bradfitz): let ServeHTTP handlers handle
  1221		// requests with non-standard expectation[s]? Seems
  1222		// theoretical at best, and doesn't fit into the
  1223		// current ServeHTTP model anyway.  We'd need to
  1224		// make the ResponseWriter an optional
  1225		// "ExpectReplier" interface or something.
  1226		//
  1227		// For now we'll just obey RFC 2616 14.20 which says
  1228		// "If a server receives a request containing an
  1229		// Expect field that includes an expectation-
  1230		// extension that it does not support, it MUST
  1231		// respond with a 417 (Expectation Failed) status."
  1232		w.Header().Set("Connection", "close")
  1233		w.WriteHeader(StatusExpectationFailed)
  1234		w.finishRequest()
  1235	}
  1236	
  1237	// Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
  1238	// and a Hijacker.
  1239	func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
  1240		if w.wroteHeader {
  1241			w.cw.flush()
  1242		}
  1243		// Release the bufioWriter that writes to the chunk writer, it is not
  1244		// used after a connection has been hijacked.
  1245		rwc, buf, err = w.conn.hijack()
  1246		if err == nil {
  1247			putBufioWriter(w.w)
  1248			w.w = nil
  1249		}
  1250		return rwc, buf, err
  1251	}
  1252	
  1253	func (w *response) CloseNotify() <-chan bool {
  1254		return w.conn.closeNotify()
  1255	}
  1256	
  1257	// The HandlerFunc type is an adapter to allow the use of
  1258	// ordinary functions as HTTP handlers.  If f is a function
  1259	// with the appropriate signature, HandlerFunc(f) is a
  1260	// Handler object that calls f.
  1261	type HandlerFunc func(ResponseWriter, *Request)
  1262	
  1263	// ServeHTTP calls f(w, r).
  1264	func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
  1265		f(w, r)
  1266	}
  1267	
  1268	// Helper handlers
  1269	
  1270	// Error replies to the request with the specified error message and HTTP code.
  1271	// The error message should be plain text.
  1272	func Error(w ResponseWriter, error string, code int) {
  1273		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  1274		w.WriteHeader(code)
  1275		fmt.Fprintln(w, error)
  1276	}
  1277	
  1278	// NotFound replies to the request with an HTTP 404 not found error.
  1279	func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
  1280	
  1281	// NotFoundHandler returns a simple request handler
  1282	// that replies to each request with a ``404 page not found'' reply.
  1283	func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
  1284	
  1285	// StripPrefix returns a handler that serves HTTP requests
  1286	// by removing the given prefix from the request URL's Path
  1287	// and invoking the handler h. StripPrefix handles a
  1288	// request for a path that doesn't begin with prefix by
  1289	// replying with an HTTP 404 not found error.
  1290	func StripPrefix(prefix string, h Handler) Handler {
  1291		if prefix == "" {
  1292			return h
  1293		}
  1294		return HandlerFunc(func(w ResponseWriter, r *Request) {
  1295			if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
  1296				r.URL.Path = p
  1297				h.ServeHTTP(w, r)
  1298			} else {
  1299				NotFound(w, r)
  1300			}
  1301		})
  1302	}
  1303	
  1304	// Redirect replies to the request with a redirect to url,
  1305	// which may be a path relative to the request path.
  1306	func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
  1307		if u, err := url.Parse(urlStr); err == nil {
  1308			// If url was relative, make absolute by
  1309			// combining with request path.
  1310			// The browser would probably do this for us,
  1311			// but doing it ourselves is more reliable.
  1312	
  1313			// NOTE(rsc): RFC 2616 says that the Location
  1314			// line must be an absolute URI, like
  1315			// "http://www.google.com/redirect/",
  1316			// not a path like "/redirect/".
  1317			// Unfortunately, we don't know what to
  1318			// put in the host name section to get the
  1319			// client to connect to us again, so we can't
  1320			// know the right absolute URI to send back.
  1321			// Because of this problem, no one pays attention
  1322			// to the RFC; they all send back just a new path.
  1323			// So do we.
  1324			oldpath := r.URL.Path
  1325			if oldpath == "" { // should not happen, but avoid a crash if it does
  1326				oldpath = "/"
  1327			}
  1328			if u.Scheme == "" {
  1329				// no leading http://server
  1330				if urlStr == "" || urlStr[0] != '/' {
  1331					// make relative path absolute
  1332					olddir, _ := path.Split(oldpath)
  1333					urlStr = olddir + urlStr
  1334				}
  1335	
  1336				var query string
  1337				if i := strings.Index(urlStr, "?"); i != -1 {
  1338					urlStr, query = urlStr[:i], urlStr[i:]
  1339				}
  1340	
  1341				// clean up but preserve trailing slash
  1342				trailing := strings.HasSuffix(urlStr, "/")
  1343				urlStr = path.Clean(urlStr)
  1344				if trailing && !strings.HasSuffix(urlStr, "/") {
  1345					urlStr += "/"
  1346				}
  1347				urlStr += query
  1348			}
  1349		}
  1350	
  1351		w.Header().Set("Location", urlStr)
  1352		w.WriteHeader(code)
  1353	
  1354		// RFC2616 recommends that a short note "SHOULD" be included in the
  1355		// response because older user agents may not understand 301/307.
  1356		// Shouldn't send the response for POST or HEAD; that leaves GET.
  1357		if r.Method == "GET" {
  1358			note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
  1359			fmt.Fprintln(w, note)
  1360		}
  1361	}
  1362	
  1363	var htmlReplacer = strings.NewReplacer(
  1364		"&", "&amp;",
  1365		"<", "&lt;",
  1366		">", "&gt;",
  1367		// "&#34;" is shorter than "&quot;".
  1368		`"`, "&#34;",
  1369		// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
  1370		"'", "&#39;",
  1371	)
  1372	
  1373	func htmlEscape(s string) string {
  1374		return htmlReplacer.Replace(s)
  1375	}
  1376	
  1377	// Redirect to a fixed URL
  1378	type redirectHandler struct {
  1379		url  string
  1380		code int
  1381	}
  1382	
  1383	func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
  1384		Redirect(w, r, rh.url, rh.code)
  1385	}
  1386	
  1387	// RedirectHandler returns a request handler that redirects
  1388	// each request it receives to the given url using the given
  1389	// status code.
  1390	func RedirectHandler(url string, code int) Handler {
  1391		return &redirectHandler{url, code}
  1392	}
  1393	
  1394	// ServeMux is an HTTP request multiplexer.
  1395	// It matches the URL of each incoming request against a list of registered
  1396	// patterns and calls the handler for the pattern that
  1397	// most closely matches the URL.
  1398	//
  1399	// Patterns name fixed, rooted paths, like "/favicon.ico",
  1400	// or rooted subtrees, like "/images/" (note the trailing slash).
  1401	// Longer patterns take precedence over shorter ones, so that
  1402	// if there are handlers registered for both "/images/"
  1403	// and "/images/thumbnails/", the latter handler will be
  1404	// called for paths beginning "/images/thumbnails/" and the
  1405	// former will receive requests for any other paths in the
  1406	// "/images/" subtree.
  1407	//
  1408	// Note that since a pattern ending in a slash names a rooted subtree,
  1409	// the pattern "/" matches all paths not matched by other registered
  1410	// patterns, not just the URL with Path == "/".
  1411	//
  1412	// Patterns may optionally begin with a host name, restricting matches to
  1413	// URLs on that host only.  Host-specific patterns take precedence over
  1414	// general patterns, so that a handler might register for the two patterns
  1415	// "/codesearch" and "codesearch.google.com/" without also taking over
  1416	// requests for "http://www.google.com/".
  1417	//
  1418	// ServeMux also takes care of sanitizing the URL request path,
  1419	// redirecting any request containing . or .. elements to an
  1420	// equivalent .- and ..-free URL.
  1421	type ServeMux struct {
  1422		mu    sync.RWMutex
  1423		m     map[string]muxEntry
  1424		hosts bool // whether any patterns contain hostnames
  1425	}
  1426	
  1427	type muxEntry struct {
  1428		explicit bool
  1429		h        Handler
  1430		pattern  string
  1431	}
  1432	
  1433	// NewServeMux allocates and returns a new ServeMux.
  1434	func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} }
  1435	
  1436	// DefaultServeMux is the default ServeMux used by Serve.
  1437	var DefaultServeMux = NewServeMux()
  1438	
  1439	// Does path match pattern?
  1440	func pathMatch(pattern, path string) bool {
  1441		if len(pattern) == 0 {
  1442			// should not happen
  1443			return false
  1444		}
  1445		n := len(pattern)
  1446		if pattern[n-1] != '/' {
  1447			return pattern == path
  1448		}
  1449		return len(path) >= n && path[0:n] == pattern
  1450	}
  1451	
  1452	// Return the canonical path for p, eliminating . and .. elements.
  1453	func cleanPath(p string) string {
  1454		if p == "" {
  1455			return "/"
  1456		}
  1457		if p[0] != '/' {
  1458			p = "/" + p
  1459		}
  1460		np := path.Clean(p)
  1461		// path.Clean removes trailing slash except for root;
  1462		// put the trailing slash back if necessary.
  1463		if p[len(p)-1] == '/' && np != "/" {
  1464			np += "/"
  1465		}
  1466		return np
  1467	}
  1468	
  1469	// Find a handler on a handler map given a path string
  1470	// Most-specific (longest) pattern wins
  1471	func (mux *ServeMux) match(path string) (h Handler, pattern string) {
  1472		var n = 0
  1473		for k, v := range mux.m {
  1474			if !pathMatch(k, path) {
  1475				continue
  1476			}
  1477			if h == nil || len(k) > n {
  1478				n = len(k)
  1479				h = v.h
  1480				pattern = v.pattern
  1481			}
  1482		}
  1483		return
  1484	}
  1485	
  1486	// Handler returns the handler to use for the given request,
  1487	// consulting r.Method, r.Host, and r.URL.Path. It always returns
  1488	// a non-nil handler. If the path is not in its canonical form, the
  1489	// handler will be an internally-generated handler that redirects
  1490	// to the canonical path.
  1491	//
  1492	// Handler also returns the registered pattern that matches the
  1493	// request or, in the case of internally-generated redirects,
  1494	// the pattern that will match after following the redirect.
  1495	//
  1496	// If there is no registered handler that applies to the request,
  1497	// Handler returns a ``page not found'' handler and an empty pattern.
  1498	func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
  1499		if r.Method != "CONNECT" {
  1500			if p := cleanPath(r.URL.Path); p != r.URL.Path {
  1501				_, pattern = mux.handler(r.Host, p)
  1502				url := *r.URL
  1503				url.Path = p
  1504				return RedirectHandler(url.String(), StatusMovedPermanently), pattern
  1505			}
  1506		}
  1507	
  1508		return mux.handler(r.Host, r.URL.Path)
  1509	}
  1510	
  1511	// handler is the main implementation of Handler.
  1512	// The path is known to be in canonical form, except for CONNECT methods.
  1513	func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
  1514		mux.mu.RLock()
  1515		defer mux.mu.RUnlock()
  1516	
  1517		// Host-specific pattern takes precedence over generic ones
  1518		if mux.hosts {
  1519			h, pattern = mux.match(host + path)
  1520		}
  1521		if h == nil {
  1522			h, pattern = mux.match(path)
  1523		}
  1524		if h == nil {
  1525			h, pattern = NotFoundHandler(), ""
  1526		}
  1527		return
  1528	}
  1529	
  1530	// ServeHTTP dispatches the request to the handler whose
  1531	// pattern most closely matches the request URL.
  1532	func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
  1533		if r.RequestURI == "*" {
  1534			if r.ProtoAtLeast(1, 1) {
  1535				w.Header().Set("Connection", "close")
  1536			}
  1537			w.WriteHeader(StatusBadRequest)
  1538			return
  1539		}
  1540		h, _ := mux.Handler(r)
  1541		h.ServeHTTP(w, r)
  1542	}
  1543	
  1544	// Handle registers the handler for the given pattern.
  1545	// If a handler already exists for pattern, Handle panics.
  1546	func (mux *ServeMux) Handle(pattern string, handler Handler) {
  1547		mux.mu.Lock()
  1548		defer mux.mu.Unlock()
  1549	
  1550		if pattern == "" {
  1551			panic("http: invalid pattern " + pattern)
  1552		}
  1553		if handler == nil {
  1554			panic("http: nil handler")
  1555		}
  1556		if mux.m[pattern].explicit {
  1557			panic("http: multiple registrations for " + pattern)
  1558		}
  1559	
  1560		mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
  1561	
  1562		if pattern[0] != '/' {
  1563			mux.hosts = true
  1564		}
  1565	
  1566		// Helpful behavior:
  1567		// If pattern is /tree/, insert an implicit permanent redirect for /tree.
  1568		// It can be overridden by an explicit registration.
  1569		n := len(pattern)
  1570		if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
  1571			// If pattern contains a host name, strip it and use remaining
  1572			// path for redirect.
  1573			path := pattern
  1574			if pattern[0] != '/' {
  1575				// In pattern, at least the last character is a '/', so
  1576				// strings.Index can't be -1.
  1577				path = pattern[strings.Index(pattern, "/"):]
  1578			}
  1579			mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(path, StatusMovedPermanently), pattern: pattern}
  1580		}
  1581	}
  1582	
  1583	// HandleFunc registers the handler function for the given pattern.
  1584	func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  1585		mux.Handle(pattern, HandlerFunc(handler))
  1586	}
  1587	
  1588	// Handle registers the handler for the given pattern
  1589	// in the DefaultServeMux.
  1590	// The documentation for ServeMux explains how patterns are matched.
  1591	func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
  1592	
  1593	// HandleFunc registers the handler function for the given pattern
  1594	// in the DefaultServeMux.
  1595	// The documentation for ServeMux explains how patterns are matched.
  1596	func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  1597		DefaultServeMux.HandleFunc(pattern, handler)
  1598	}
  1599	
  1600	// Serve accepts incoming HTTP connections on the listener l,
  1601	// creating a new service goroutine for each.  The service goroutines
  1602	// read requests and then call handler to reply to them.
  1603	// Handler is typically nil, in which case the DefaultServeMux is used.
  1604	func Serve(l net.Listener, handler Handler) error {
  1605		srv := &Server{Handler: handler}
  1606		return srv.Serve(l)
  1607	}
  1608	
  1609	// A Server defines parameters for running an HTTP server.
  1610	// The zero value for Server is a valid configuration.
  1611	type Server struct {
  1612		Addr           string        // TCP address to listen on, ":http" if empty
  1613		Handler        Handler       // handler to invoke, http.DefaultServeMux if nil
  1614		ReadTimeout    time.Duration // maximum duration before timing out read of the request
  1615		WriteTimeout   time.Duration // maximum duration before timing out write of the response
  1616		MaxHeaderBytes int           // maximum size of request headers, DefaultMaxHeaderBytes if 0
  1617		TLSConfig      *tls.Config   // optional TLS config, used by ListenAndServeTLS
  1618	
  1619		// TLSNextProto optionally specifies a function to take over
  1620		// ownership of the provided TLS connection when an NPN
  1621		// protocol upgrade has occurred.  The map key is the protocol
  1622		// name negotiated. The Handler argument should be used to
  1623		// handle HTTP requests and will initialize the Request's TLS
  1624		// and RemoteAddr if not already set.  The connection is
  1625		// automatically closed when the function returns.
  1626		TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
  1627	
  1628		// ConnState specifies an optional callback function that is
  1629		// called when a client connection changes state. See the
  1630		// ConnState type and associated constants for details.
  1631		ConnState func(net.Conn, ConnState)
  1632	
  1633		// ErrorLog specifies an optional logger for errors accepting
  1634		// connections and unexpected behavior from handlers.
  1635		// If nil, logging goes to os.Stderr via the log package's
  1636		// standard logger.
  1637		ErrorLog *log.Logger
  1638	
  1639		disableKeepAlives int32 // accessed atomically.
  1640	}
  1641	
  1642	// A ConnState represents the state of a client connection to a server.
  1643	// It's used by the optional Server.ConnState hook.
  1644	type ConnState int
  1645	
  1646	const (
  1647		// StateNew represents a new connection that is expected to
  1648		// send a request immediately. Connections begin at this
  1649		// state and then transition to either StateActive or
  1650		// StateClosed.
  1651		StateNew ConnState = iota
  1652	
  1653		// StateActive represents a connection that has read 1 or more
  1654		// bytes of a request. The Server.ConnState hook for
  1655		// StateActive fires before the request has entered a handler
  1656		// and doesn't fire again until the request has been
  1657		// handled. After the request is handled, the state
  1658		// transitions to StateClosed, StateHijacked, or StateIdle.
  1659		StateActive
  1660	
  1661		// StateIdle represents a connection that has finished
  1662		// handling a request and is in the keep-alive state, waiting
  1663		// for a new request. Connections transition from StateIdle
  1664		// to either StateActive or StateClosed.
  1665		StateIdle
  1666	
  1667		// StateHijacked represents a hijacked connection.
  1668		// This is a terminal state. It does not transition to StateClosed.
  1669		StateHijacked
  1670	
  1671		// StateClosed represents a closed connection.
  1672		// This is a terminal state. Hijacked connections do not
  1673		// transition to StateClosed.
  1674		StateClosed
  1675	)
  1676	
  1677	var stateName = map[ConnState]string{
  1678		StateNew:      "new",
  1679		StateActive:   "active",
  1680		StateIdle:     "idle",
  1681		StateHijacked: "hijacked",
  1682		StateClosed:   "closed",
  1683	}
  1684	
  1685	func (c ConnState) String() string {
  1686		return stateName[c]
  1687	}
  1688	
  1689	// serverHandler delegates to either the server's Handler or
  1690	// DefaultServeMux and also handles "OPTIONS *" requests.
  1691	type serverHandler struct {
  1692		srv *Server
  1693	}
  1694	
  1695	func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
  1696		handler := sh.srv.Handler
  1697		if handler == nil {
  1698			handler = DefaultServeMux
  1699		}
  1700		if req.RequestURI == "*" && req.Method == "OPTIONS" {
  1701			handler = globalOptionsHandler{}
  1702		}
  1703		handler.ServeHTTP(rw, req)
  1704	}
  1705	
  1706	// ListenAndServe listens on the TCP network address srv.Addr and then
  1707	// calls Serve to handle requests on incoming connections.  If
  1708	// srv.Addr is blank, ":http" is used.
  1709	func (srv *Server) ListenAndServe() error {
  1710		addr := srv.Addr
  1711		if addr == "" {
  1712			addr = ":http"
  1713		}
  1714		ln, err := net.Listen("tcp", addr)
  1715		if err != nil {
  1716			return err
  1717		}
  1718		return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
  1719	}
  1720	
  1721	// Serve accepts incoming connections on the Listener l, creating a
  1722	// new service goroutine for each.  The service goroutines read requests and
  1723	// then call srv.Handler to reply to them.
  1724	func (srv *Server) Serve(l net.Listener) error {
  1725		defer l.Close()
  1726		var tempDelay time.Duration // how long to sleep on accept failure
  1727		for {
  1728			rw, e := l.Accept()
  1729			if e != nil {
  1730				if ne, ok := e.(net.Error); ok && ne.Temporary() {
  1731					if tempDelay == 0 {
  1732						tempDelay = 5 * time.Millisecond
  1733					} else {
  1734						tempDelay *= 2
  1735					}
  1736					if max := 1 * time.Second; tempDelay > max {
  1737						tempDelay = max
  1738					}
  1739					srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
  1740					time.Sleep(tempDelay)
  1741					continue
  1742				}
  1743				return e
  1744			}
  1745			tempDelay = 0
  1746			c, err := srv.newConn(rw)
  1747			if err != nil {
  1748				continue
  1749			}
  1750			c.setState(c.rwc, StateNew) // before Serve can return
  1751			go c.serve()
  1752		}
  1753	}
  1754	
  1755	func (s *Server) doKeepAlives() bool {
  1756		return atomic.LoadInt32(&s.disableKeepAlives) == 0
  1757	}
  1758	
  1759	// SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
  1760	// By default, keep-alives are always enabled. Only very
  1761	// resource-constrained environments or servers in the process of
  1762	// shutting down should disable them.
  1763	func (s *Server) SetKeepAlivesEnabled(v bool) {
  1764		if v {
  1765			atomic.StoreInt32(&s.disableKeepAlives, 0)
  1766		} else {
  1767			atomic.StoreInt32(&s.disableKeepAlives, 1)
  1768		}
  1769	}
  1770	
  1771	func (s *Server) logf(format string, args ...interface{}) {
  1772		if s.ErrorLog != nil {
  1773			s.ErrorLog.Printf(format, args...)
  1774		} else {
  1775			log.Printf(format, args...)
  1776		}
  1777	}
  1778	
  1779	// ListenAndServe listens on the TCP network address addr
  1780	// and then calls Serve with handler to handle requests
  1781	// on incoming connections.  Handler is typically nil,
  1782	// in which case the DefaultServeMux is used.
  1783	//
  1784	// A trivial example server is:
  1785	//
  1786	//	package main
  1787	//
  1788	//	import (
  1789	//		"io"
  1790	//		"net/http"
  1791	//		"log"
  1792	//	)
  1793	//
  1794	//	// hello world, the web server
  1795	//	func HelloServer(w http.ResponseWriter, req *http.Request) {
  1796	//		io.WriteString(w, "hello, world!\n")
  1797	//	}
  1798	//
  1799	//	func main() {
  1800	//		http.HandleFunc("/hello", HelloServer)
  1801	//		err := http.ListenAndServe(":12345", nil)
  1802	//		if err != nil {
  1803	//			log.Fatal("ListenAndServe: ", err)
  1804	//		}
  1805	//	}
  1806	func ListenAndServe(addr string, handler Handler) error {
  1807		server := &Server{Addr: addr, Handler: handler}
  1808		return server.ListenAndServe()
  1809	}
  1810	
  1811	// ListenAndServeTLS acts identically to ListenAndServe, except that it
  1812	// expects HTTPS connections. Additionally, files containing a certificate and
  1813	// matching private key for the server must be provided. If the certificate
  1814	// is signed by a certificate authority, the certFile should be the concatenation
  1815	// of the server's certificate followed by the CA's certificate.
  1816	//
  1817	// A trivial example server is:
  1818	//
  1819	//	import (
  1820	//		"log"
  1821	//		"net/http"
  1822	//	)
  1823	//
  1824	//	func handler(w http.ResponseWriter, req *http.Request) {
  1825	//		w.Header().Set("Content-Type", "text/plain")
  1826	//		w.Write([]byte("This is an example server.\n"))
  1827	//	}
  1828	//
  1829	//	func main() {
  1830	//		http.HandleFunc("/", handler)
  1831	//		log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
  1832	//		err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
  1833	//		if err != nil {
  1834	//			log.Fatal(err)
  1835	//		}
  1836	//	}
  1837	//
  1838	// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
  1839	func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
  1840		server := &Server{Addr: addr, Handler: handler}
  1841		return server.ListenAndServeTLS(certFile, keyFile)
  1842	}
  1843	
  1844	// ListenAndServeTLS listens on the TCP network address srv.Addr and
  1845	// then calls Serve to handle requests on incoming TLS connections.
  1846	//
  1847	// Filenames containing a certificate and matching private key for
  1848	// the server must be provided. If the certificate is signed by a
  1849	// certificate authority, the certFile should be the concatenation
  1850	// of the server's certificate followed by the CA's certificate.
  1851	//
  1852	// If srv.Addr is blank, ":https" is used.
  1853	func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
  1854		addr := srv.Addr
  1855		if addr == "" {
  1856			addr = ":https"
  1857		}
  1858		config := &tls.Config{}
  1859		if srv.TLSConfig != nil {
  1860			*config = *srv.TLSConfig
  1861		}
  1862		if config.NextProtos == nil {
  1863			config.NextProtos = []string{"http/1.1"}
  1864		}
  1865	
  1866		var err error
  1867		config.Certificates = make([]tls.Certificate, 1)
  1868		config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  1869		if err != nil {
  1870			return err
  1871		}
  1872	
  1873		ln, err := net.Listen("tcp", addr)
  1874		if err != nil {
  1875			return err
  1876		}
  1877	
  1878		tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)
  1879		return srv.Serve(tlsListener)
  1880	}
  1881	
  1882	// TimeoutHandler returns a Handler that runs h with the given time limit.
  1883	//
  1884	// The new Handler calls h.ServeHTTP to handle each request, but if a
  1885	// call runs for longer than its time limit, the handler responds with
  1886	// a 503 Service Unavailable error and the given message in its body.
  1887	// (If msg is empty, a suitable default message will be sent.)
  1888	// After such a timeout, writes by h to its ResponseWriter will return
  1889	// ErrHandlerTimeout.
  1890	func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
  1891		f := func() <-chan time.Time {
  1892			return time.After(dt)
  1893		}
  1894		return &timeoutHandler{h, f, msg}
  1895	}
  1896	
  1897	// ErrHandlerTimeout is returned on ResponseWriter Write calls
  1898	// in handlers which have timed out.
  1899	var ErrHandlerTimeout = errors.New("http: Handler timeout")
  1900	
  1901	type timeoutHandler struct {
  1902		handler Handler
  1903		timeout func() <-chan time.Time // returns channel producing a timeout
  1904		body    string
  1905	}
  1906	
  1907	func (h *timeoutHandler) errorBody() string {
  1908		if h.body != "" {
  1909			return h.body
  1910		}
  1911		return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
  1912	}
  1913	
  1914	func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
  1915		done := make(chan bool, 1)
  1916		tw := &timeoutWriter{w: w}
  1917		go func() {
  1918			h.handler.ServeHTTP(tw, r)
  1919			done <- true
  1920		}()
  1921		select {
  1922		case <-done:
  1923			return
  1924		case <-h.timeout():
  1925			tw.mu.Lock()
  1926			defer tw.mu.Unlock()
  1927			if !tw.wroteHeader {
  1928				tw.w.WriteHeader(StatusServiceUnavailable)
  1929				tw.w.Write([]byte(h.errorBody()))
  1930			}
  1931			tw.timedOut = true
  1932		}
  1933	}
  1934	
  1935	type timeoutWriter struct {
  1936		w ResponseWriter
  1937	
  1938		mu          sync.Mutex
  1939		timedOut    bool
  1940		wroteHeader bool
  1941	}
  1942	
  1943	func (tw *timeoutWriter) Header() Header {
  1944		return tw.w.Header()
  1945	}
  1946	
  1947	func (tw *timeoutWriter) Write(p []byte) (int, error) {
  1948		tw.mu.Lock()
  1949		defer tw.mu.Unlock()
  1950		tw.wroteHeader = true // implicitly at least
  1951		if tw.timedOut {
  1952			return 0, ErrHandlerTimeout
  1953		}
  1954		return tw.w.Write(p)
  1955	}
  1956	
  1957	func (tw *timeoutWriter) WriteHeader(code int) {
  1958		tw.mu.Lock()
  1959		defer tw.mu.Unlock()
  1960		if tw.timedOut || tw.wroteHeader {
  1961			return
  1962		}
  1963		tw.wroteHeader = true
  1964		tw.w.WriteHeader(code)
  1965	}
  1966	
  1967	// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
  1968	// connections. It's used by ListenAndServe and ListenAndServeTLS so
  1969	// dead TCP connections (e.g. closing laptop mid-download) eventually
  1970	// go away.
  1971	type tcpKeepAliveListener struct {
  1972		*net.TCPListener
  1973	}
  1974	
  1975	func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  1976		tc, err := ln.AcceptTCP()
  1977		if err != nil {
  1978			return
  1979		}
  1980		tc.SetKeepAlive(true)
  1981		tc.SetKeepAlivePeriod(3 * time.Minute)
  1982		return tc, nil
  1983	}
  1984	
  1985	// globalOptionsHandler responds to "OPTIONS *" requests.
  1986	type globalOptionsHandler struct{}
  1987	
  1988	func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
  1989		w.Header().Set("Content-Length", "0")
  1990		if r.ContentLength != 0 {
  1991			// Read up to 4KB of OPTIONS body (as mentioned in the
  1992			// spec as being reserved for future use), but anything
  1993			// over that is considered a waste of server resources
  1994			// (or an attack) and we abort and close the connection,
  1995			// courtesy of MaxBytesReader's EOF behavior.
  1996			mb := MaxBytesReader(w, r.Body, 4<<10)
  1997			io.Copy(ioutil.Discard, mb)
  1998		}
  1999	}
  2000	
  2001	type eofReaderWithWriteTo struct{}
  2002	
  2003	func (eofReaderWithWriteTo) WriteTo(io.Writer) (int64, error) { return 0, nil }
  2004	func (eofReaderWithWriteTo) Read([]byte) (int, error)         { return 0, io.EOF }
  2005	
  2006	// eofReader is a non-nil io.ReadCloser that always returns EOF.
  2007	// It has a WriteTo method so io.Copy won't need a buffer.
  2008	var eofReader = &struct {
  2009		eofReaderWithWriteTo
  2010		io.Closer
  2011	}{
  2012		eofReaderWithWriteTo{},
  2013		ioutil.NopCloser(nil),
  2014	}
  2015	
  2016	// Verify that an io.Copy from an eofReader won't require a buffer.
  2017	var _ io.WriterTo = eofReader
  2018	
  2019	// initNPNRequest is an HTTP handler that initializes certain
  2020	// uninitialized fields in its *Request. Such partially-initialized
  2021	// Requests come from NPN protocol handlers.
  2022	type initNPNRequest struct {
  2023		c *tls.Conn
  2024		h serverHandler
  2025	}
  2026	
  2027	func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
  2028		if req.TLS == nil {
  2029			req.TLS = &tls.ConnectionState{}
  2030			*req.TLS = h.c.ConnectionState()
  2031		}
  2032		if req.Body == nil {
  2033			req.Body = eofReader
  2034		}
  2035		if req.RemoteAddr == "" {
  2036			req.RemoteAddr = h.c.RemoteAddr().String()
  2037		}
  2038		h.h.ServeHTTP(rw, req)
  2039	}
  2040	
  2041	// loggingConn is used for debugging.
  2042	type loggingConn struct {
  2043		name string
  2044		net.Conn
  2045	}
  2046	
  2047	var (
  2048		uniqNameMu   sync.Mutex
  2049		uniqNameNext = make(map[string]int)
  2050	)
  2051	
  2052	func newLoggingConn(baseName string, c net.Conn) net.Conn {
  2053		uniqNameMu.Lock()
  2054		defer uniqNameMu.Unlock()
  2055		uniqNameNext[baseName]++
  2056		return &loggingConn{
  2057			name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
  2058			Conn: c,
  2059		}
  2060	}
  2061	
  2062	func (c *loggingConn) Write(p []byte) (n int, err error) {
  2063		log.Printf("%s.Write(%d) = ....", c.name, len(p))
  2064		n, err = c.Conn.Write(p)
  2065		log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
  2066		return
  2067	}
  2068	
  2069	func (c *loggingConn) Read(p []byte) (n int, err error) {
  2070		log.Printf("%s.Read(%d) = ....", c.name, len(p))
  2071		n, err = c.Conn.Read(p)
  2072		log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
  2073		return
  2074	}
  2075	
  2076	func (c *loggingConn) Close() (err error) {
  2077		log.Printf("%s.Close() = ...", c.name)
  2078		err = c.Conn.Close()
  2079		log.Printf("%s.Close() = %v", c.name, err)
  2080		return
  2081	}
  2082	
  2083	// checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
  2084	// It only contains one field (and a pointer field at that), so it
  2085	// fits in an interface value without an extra allocation.
  2086	type checkConnErrorWriter struct {
  2087		c *conn
  2088	}
  2089	
  2090	func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
  2091		n, err = w.c.w.Write(p) // c.w == c.rwc, except after a hijack, when rwc is nil.
  2092		if err != nil && w.c.werr == nil {
  2093			w.c.werr = err
  2094		}
  2095		return
  2096	}
  2097	

View as plain text