github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/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  	"errors"
    12  	"io"
    13  	"net/textproto"
    14  	"net/url"
    15  	"strconv"
    16  	"strings"
    17  )
    18  
    19  var respExcludeHeader = map[string]bool{
    20  	"Content-Length":    true,
    21  	"Transfer-Encoding": true,
    22  	"Trailer":           true,
    23  }
    24  
    25  // Response represents the response from an HTTP request.
    26  //
    27  type Response struct {
    28  	Status     string // e.g. "200 OK"
    29  	StatusCode int    // e.g. 200
    30  	Proto      string // e.g. "HTTP/1.0"
    31  	ProtoMajor int    // e.g. 1
    32  	ProtoMinor int    // e.g. 0
    33  
    34  	// Header maps header keys to values.  If the response had multiple
    35  	// headers with the same key, they will be concatenated, with comma
    36  	// delimiters.  (Section 4.2 of RFC 2616 requires that multiple headers
    37  	// be semantically equivalent to a comma-delimited sequence.) Values
    38  	// duplicated by other fields in this struct (e.g., ContentLength) are
    39  	// omitted from Header.
    40  	//
    41  	// Keys in the map are canonicalized (see CanonicalHeaderKey).
    42  	Header Header
    43  
    44  	// Body represents the response body.
    45  	//
    46  	// The http Client and Transport guarantee that Body is always
    47  	// non-nil, even on responses without a body or responses with
    48  	// a zero-lengthed body.
    49  	//
    50  	// The Body is automatically dechunked if the server replied
    51  	// with a "chunked" Transfer-Encoding.
    52  	Body io.ReadCloser
    53  
    54  	// ContentLength records the length of the associated content.  The
    55  	// value -1 indicates that the length is unknown.  Unless Request.Method
    56  	// is "HEAD", values >= 0 indicate that the given number of bytes may
    57  	// be read from Body.
    58  	ContentLength int64
    59  
    60  	// Contains transfer encodings from outer-most to inner-most. Value is
    61  	// nil, means that "identity" encoding is used.
    62  	TransferEncoding []string
    63  
    64  	// Close records whether the header directed that the connection be
    65  	// closed after reading Body.  The value is advice for clients: neither
    66  	// ReadResponse nor Response.Write ever closes a connection.
    67  	Close bool
    68  
    69  	// Trailer maps trailer keys to values, in the same
    70  	// format as the header.
    71  	Trailer Header
    72  
    73  	// The Request that was sent to obtain this Response.
    74  	// Request's Body is nil (having already been consumed).
    75  	// This is only populated for Client requests.
    76  	Request *Request
    77  }
    78  
    79  // Cookies parses and returns the cookies set in the Set-Cookie headers.
    80  func (r *Response) Cookies() []*Cookie {
    81  	return readSetCookies(r.Header)
    82  }
    83  
    84  var ErrNoLocation = errors.New("http: no Location header in response")
    85  
    86  // Location returns the URL of the response's "Location" header,
    87  // if present.  Relative redirects are resolved relative to
    88  // the Response's Request.  ErrNoLocation is returned if no
    89  // Location header is present.
    90  func (r *Response) Location() (*url.URL, error) {
    91  	lv := r.Header.Get("Location")
    92  	if lv == "" {
    93  		return nil, ErrNoLocation
    94  	}
    95  	if r.Request != nil && r.Request.URL != nil {
    96  		return r.Request.URL.Parse(lv)
    97  	}
    98  	return url.Parse(lv)
    99  }
   100  
   101  // ReadResponse reads and returns an HTTP response from r.  The
   102  // req parameter specifies the Request that corresponds to
   103  // this Response.  Clients must call resp.Body.Close when finished
   104  // reading resp.Body.  After that call, clients can inspect
   105  // resp.Trailer to find key/value pairs included in the response
   106  // trailer.
   107  func ReadResponse(r *bufio.Reader, req *Request) (resp *Response, err error) {
   108  
   109  	tp := textproto.NewReader(r)
   110  	resp = new(Response)
   111  
   112  	resp.Request = req
   113  
   114  	// Parse the first line of the response.
   115  	line, err := tp.ReadLine()
   116  	if err != nil {
   117  		if err == io.EOF {
   118  			err = io.ErrUnexpectedEOF
   119  		}
   120  		return nil, err
   121  	}
   122  	f := strings.SplitN(line, " ", 3)
   123  	if len(f) < 2 {
   124  		return nil, &badStringError{"malformed HTTP response", line}
   125  	}
   126  	reasonPhrase := ""
   127  	if len(f) > 2 {
   128  		reasonPhrase = f[2]
   129  	}
   130  	resp.Status = f[1] + " " + reasonPhrase
   131  	resp.StatusCode, err = strconv.Atoi(f[1])
   132  	if err != nil {
   133  		return nil, &badStringError{"malformed HTTP status code", f[1]}
   134  	}
   135  
   136  	resp.Proto = f[0]
   137  	var ok bool
   138  	if resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {
   139  		return nil, &badStringError{"malformed HTTP version", resp.Proto}
   140  	}
   141  
   142  	// Parse the response headers.
   143  	mimeHeader, err := tp.ReadMIMEHeader()
   144  	if err != nil {
   145  		return nil, err
   146  	}
   147  	resp.Header = Header(mimeHeader)
   148  
   149  	fixPragmaCacheControl(resp.Header)
   150  
   151  	err = readTransfer(resp, r)
   152  	if err != nil {
   153  		return nil, err
   154  	}
   155  
   156  	return resp, nil
   157  }
   158  
   159  // RFC2616: Should treat
   160  //	Pragma: no-cache
   161  // like
   162  //	Cache-Control: no-cache
   163  func fixPragmaCacheControl(header Header) {
   164  	if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" {
   165  		if _, presentcc := header["Cache-Control"]; !presentcc {
   166  			header["Cache-Control"] = []string{"no-cache"}
   167  		}
   168  	}
   169  }
   170  
   171  // ProtoAtLeast returns whether the HTTP protocol used
   172  // in the response is at least major.minor.
   173  func (r *Response) ProtoAtLeast(major, minor int) bool {
   174  	return r.ProtoMajor > major ||
   175  		r.ProtoMajor == major && r.ProtoMinor >= minor
   176  }
   177  
   178  // Writes the response (header, body and trailer) in wire format. This method
   179  // consults the following fields of the response:
   180  //
   181  //  StatusCode
   182  //  ProtoMajor
   183  //  ProtoMinor
   184  //  Request.Method
   185  //  TransferEncoding
   186  //  Trailer
   187  //  Body
   188  //  ContentLength
   189  //  Header, values for non-canonical keys will have unpredictable behavior
   190  //
   191  func (r *Response) Write(w io.Writer) error {
   192  
   193  	// Status line
   194  	text := r.Status
   195  	if text == "" {
   196  		var ok bool
   197  		text, ok = statusText[r.StatusCode]
   198  		if !ok {
   199  			text = "status code " + strconv.Itoa(r.StatusCode)
   200  		}
   201  	}
   202  	protoMajor, protoMinor := strconv.Itoa(r.ProtoMajor), strconv.Itoa(r.ProtoMinor)
   203  	statusCode := strconv.Itoa(r.StatusCode) + " "
   204  	text = strings.TrimPrefix(text, statusCode)
   205  	io.WriteString(w, "HTTP/"+protoMajor+"."+protoMinor+" "+statusCode+text+"\r\n")
   206  
   207  	// Process Body,ContentLength,Close,Trailer
   208  	tw, err := newTransferWriter(r)
   209  	if err != nil {
   210  		return err
   211  	}
   212  	err = tw.WriteHeader(w)
   213  	if err != nil {
   214  		return err
   215  	}
   216  
   217  	// Rest of header
   218  	err = r.Header.WriteSubset(w, respExcludeHeader)
   219  	if err != nil {
   220  		return err
   221  	}
   222  
   223  	// End-of-header
   224  	io.WriteString(w, "\r\n")
   225  
   226  	// Write body and trailer
   227  	err = tw.WriteBody(w)
   228  	if err != nil {
   229  		return err
   230  	}
   231  
   232  	// Success
   233  	return nil
   234  }