github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/src/net/http/response.go (about)

     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 Response reading and parsing.
     6  
     7  package http
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"crypto/tls"
    13  	"errors"
    14  	"io"
    15  	"net/textproto"
    16  	"net/url"
    17  	"strconv"
    18  	"strings"
    19  )
    20  
    21  var respExcludeHeader = map[string]bool{
    22  	"Content-Length":    true,
    23  	"Transfer-Encoding": true,
    24  	"Trailer":           true,
    25  }
    26  
    27  // Response represents the response from an HTTP request.
    28  //
    29  type Response struct {
    30  	Status     string // e.g. "200 OK"
    31  	StatusCode int    // e.g. 200
    32  	Proto      string // e.g. "HTTP/1.0"
    33  	ProtoMajor int    // e.g. 1
    34  	ProtoMinor int    // e.g. 0
    35  
    36  	// Header maps header keys to values.  If the response had multiple
    37  	// headers with the same key, they may be concatenated, with comma
    38  	// delimiters.  (Section 4.2 of RFC 2616 requires that multiple headers
    39  	// be semantically equivalent to a comma-delimited sequence.) Values
    40  	// duplicated by other fields in this struct (e.g., ContentLength) are
    41  	// omitted from Header.
    42  	//
    43  	// Keys in the map are canonicalized (see CanonicalHeaderKey).
    44  	Header Header
    45  
    46  	// Body represents the response body.
    47  	//
    48  	// The http Client and Transport guarantee that Body is always
    49  	// non-nil, even on responses without a body or responses with
    50  	// a zero-length body. It is the caller's responsibility to
    51  	// close Body. The default HTTP client's Transport does not
    52  	// attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections
    53  	// ("keep-alive") unless the Body is read to completion and is
    54  	// closed.
    55  	//
    56  	// The Body is automatically dechunked if the server replied
    57  	// with a "chunked" Transfer-Encoding.
    58  	Body io.ReadCloser
    59  
    60  	// ContentLength records the length of the associated content.  The
    61  	// value -1 indicates that the length is unknown.  Unless Request.Method
    62  	// is "HEAD", values >= 0 indicate that the given number of bytes may
    63  	// be read from Body.
    64  	ContentLength int64
    65  
    66  	// Contains transfer encodings from outer-most to inner-most. Value is
    67  	// nil, means that "identity" encoding is used.
    68  	TransferEncoding []string
    69  
    70  	// Close records whether the header directed that the connection be
    71  	// closed after reading Body.  The value is advice for clients: neither
    72  	// ReadResponse nor Response.Write ever closes a connection.
    73  	Close bool
    74  
    75  	// Trailer maps trailer keys to values, in the same
    76  	// format as the header.
    77  	Trailer Header
    78  
    79  	// The Request that was sent to obtain this Response.
    80  	// Request's Body is nil (having already been consumed).
    81  	// This is only populated for Client requests.
    82  	Request *Request
    83  
    84  	// TLS contains information about the TLS connection on which the
    85  	// response was received. It is nil for unencrypted responses.
    86  	// The pointer is shared between responses and should not be
    87  	// modified.
    88  	TLS *tls.ConnectionState
    89  }
    90  
    91  // Cookies parses and returns the cookies set in the Set-Cookie headers.
    92  func (r *Response) Cookies() []*Cookie {
    93  	return readSetCookies(r.Header)
    94  }
    95  
    96  var ErrNoLocation = errors.New("http: no Location header in response")
    97  
    98  // Location returns the URL of the response's "Location" header,
    99  // if present.  Relative redirects are resolved relative to
   100  // the Response's Request.  ErrNoLocation is returned if no
   101  // Location header is present.
   102  func (r *Response) Location() (*url.URL, error) {
   103  	lv := r.Header.Get("Location")
   104  	if lv == "" {
   105  		return nil, ErrNoLocation
   106  	}
   107  	if r.Request != nil && r.Request.URL != nil {
   108  		return r.Request.URL.Parse(lv)
   109  	}
   110  	return url.Parse(lv)
   111  }
   112  
   113  // ReadResponse reads and returns an HTTP response from r.
   114  // The req parameter optionally specifies the Request that corresponds
   115  // to this Response. If nil, a GET request is assumed.
   116  // Clients must call resp.Body.Close when finished reading resp.Body.
   117  // After that call, clients can inspect resp.Trailer to find key/value
   118  // pairs included in the response trailer.
   119  func ReadResponse(r *bufio.Reader, req *Request) (*Response, error) {
   120  	tp := textproto.NewReader(r)
   121  	resp := &Response{
   122  		Request: req,
   123  	}
   124  
   125  	// Parse the first line of the response.
   126  	line, err := tp.ReadLine()
   127  	if err != nil {
   128  		if err == io.EOF {
   129  			err = io.ErrUnexpectedEOF
   130  		}
   131  		return nil, err
   132  	}
   133  	f := strings.SplitN(line, " ", 3)
   134  	if len(f) < 2 {
   135  		return nil, &badStringError{"malformed HTTP response", line}
   136  	}
   137  	reasonPhrase := ""
   138  	if len(f) > 2 {
   139  		reasonPhrase = f[2]
   140  	}
   141  	resp.Status = f[1] + " " + reasonPhrase
   142  	resp.StatusCode, err = strconv.Atoi(f[1])
   143  	if err != nil {
   144  		return nil, &badStringError{"malformed HTTP status code", f[1]}
   145  	}
   146  
   147  	resp.Proto = f[0]
   148  	var ok bool
   149  	if resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {
   150  		return nil, &badStringError{"malformed HTTP version", resp.Proto}
   151  	}
   152  
   153  	// Parse the response headers.
   154  	mimeHeader, err := tp.ReadMIMEHeader()
   155  	if err != nil {
   156  		if err == io.EOF {
   157  			err = io.ErrUnexpectedEOF
   158  		}
   159  		return nil, err
   160  	}
   161  	resp.Header = Header(mimeHeader)
   162  
   163  	fixPragmaCacheControl(resp.Header)
   164  
   165  	err = readTransfer(resp, r)
   166  	if err != nil {
   167  		return nil, err
   168  	}
   169  
   170  	return resp, nil
   171  }
   172  
   173  // RFC2616: Should treat
   174  //	Pragma: no-cache
   175  // like
   176  //	Cache-Control: no-cache
   177  func fixPragmaCacheControl(header Header) {
   178  	if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" {
   179  		if _, presentcc := header["Cache-Control"]; !presentcc {
   180  			header["Cache-Control"] = []string{"no-cache"}
   181  		}
   182  	}
   183  }
   184  
   185  // ProtoAtLeast reports whether the HTTP protocol used
   186  // in the response is at least major.minor.
   187  func (r *Response) ProtoAtLeast(major, minor int) bool {
   188  	return r.ProtoMajor > major ||
   189  		r.ProtoMajor == major && r.ProtoMinor >= minor
   190  }
   191  
   192  // Writes the response (header, body and trailer) in wire format. This method
   193  // consults the following fields of the response:
   194  //
   195  //  StatusCode
   196  //  ProtoMajor
   197  //  ProtoMinor
   198  //  Request.Method
   199  //  TransferEncoding
   200  //  Trailer
   201  //  Body
   202  //  ContentLength
   203  //  Header, values for non-canonical keys will have unpredictable behavior
   204  //
   205  // Body is closed after it is sent.
   206  func (r *Response) Write(w io.Writer) error {
   207  	// Status line
   208  	text := r.Status
   209  	if text == "" {
   210  		var ok bool
   211  		text, ok = statusText[r.StatusCode]
   212  		if !ok {
   213  			text = "status code " + strconv.Itoa(r.StatusCode)
   214  		}
   215  	}
   216  	protoMajor, protoMinor := strconv.Itoa(r.ProtoMajor), strconv.Itoa(r.ProtoMinor)
   217  	statusCode := strconv.Itoa(r.StatusCode) + " "
   218  	text = strings.TrimPrefix(text, statusCode)
   219  	if _, err := io.WriteString(w, "HTTP/"+protoMajor+"."+protoMinor+" "+statusCode+text+"\r\n"); err != nil {
   220  		return err
   221  	}
   222  
   223  	// Clone it, so we can modify r1 as needed.
   224  	r1 := new(Response)
   225  	*r1 = *r
   226  	if r1.ContentLength == 0 && r1.Body != nil {
   227  		// Is it actually 0 length? Or just unknown?
   228  		var buf [1]byte
   229  		n, err := r1.Body.Read(buf[:])
   230  		if err != nil && err != io.EOF {
   231  			return err
   232  		}
   233  		if n == 0 {
   234  			// Reset it to a known zero reader, in case underlying one
   235  			// is unhappy being read repeatedly.
   236  			r1.Body = eofReader
   237  		} else {
   238  			r1.ContentLength = -1
   239  			r1.Body = struct {
   240  				io.Reader
   241  				io.Closer
   242  			}{
   243  				io.MultiReader(bytes.NewReader(buf[:1]), r.Body),
   244  				r.Body,
   245  			}
   246  		}
   247  	}
   248  	// If we're sending a non-chunked HTTP/1.1 response without a
   249  	// content-length, the only way to do that is the old HTTP/1.0
   250  	// way, by noting the EOF with a connection close, so we need
   251  	// to set Close.
   252  	if r1.ContentLength == -1 && !r1.Close && r1.ProtoAtLeast(1, 1) && !chunked(r1.TransferEncoding) {
   253  		r1.Close = true
   254  	}
   255  
   256  	// Process Body,ContentLength,Close,Trailer
   257  	tw, err := newTransferWriter(r1)
   258  	if err != nil {
   259  		return err
   260  	}
   261  	err = tw.WriteHeader(w)
   262  	if err != nil {
   263  		return err
   264  	}
   265  
   266  	// Rest of header
   267  	err = r.Header.WriteSubset(w, respExcludeHeader)
   268  	if err != nil {
   269  		return err
   270  	}
   271  
   272  	// contentLengthAlreadySent may have been already sent for
   273  	// POST/PUT requests, even if zero length. See Issue 8180.
   274  	contentLengthAlreadySent := tw.shouldSendContentLength()
   275  	if r1.ContentLength == 0 && !chunked(r1.TransferEncoding) && !contentLengthAlreadySent {
   276  		if _, err := io.WriteString(w, "Content-Length: 0\r\n"); err != nil {
   277  			return err
   278  		}
   279  	}
   280  
   281  	// End-of-header
   282  	if _, err := io.WriteString(w, "\r\n"); err != nil {
   283  		return err
   284  	}
   285  
   286  	// Write body and trailer
   287  	err = tw.WriteBody(w)
   288  	if err != nil {
   289  		return err
   290  	}
   291  
   292  	// Success
   293  	return nil
   294  }