1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // HTTP Response reading and parsing.
19 var respExcludeHeader = map[string]bool{
20 "Content-Length": true,
21 "Transfer-Encoding": true,
25 // Response represents the response from an HTTP request.
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
34 // Header maps header keys to values. If the response had multiple
35 // headers with the same key, they may 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.
41 // Keys in the map are canonicalized (see CanonicalHeaderKey).
44 // Body represents the response body.
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.
50 // The Body is automatically dechunked if the server replied
51 // with a "chunked" Transfer-Encoding.
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
60 // Contains transfer encodings from outer-most to inner-most. Value is
61 // nil, means that "identity" encoding is used.
62 TransferEncoding []string
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.
69 // Trailer maps trailer keys to values, in the same
70 // format as the header.
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.
79 // Cookies parses and returns the cookies set in the Set-Cookie headers.
80 func (r *Response) Cookies() []*Cookie {
81 return readSetCookies(r.Header)
84 var ErrNoLocation = errors.New("http: no Location header in response")
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")
93 return nil, ErrNoLocation
95 if r.Request != nil && r.Request.URL != nil {
96 return r.Request.URL.Parse(lv)
101 // ReadResponse reads and returns an HTTP response from r.
102 // The req parameter optionally specifies the Request that corresponds
103 // to this Response. If nil, a GET request is assumed.
104 // Clients must call resp.Body.Close when finished reading resp.Body.
105 // After that call, clients can inspect resp.Trailer to find key/value
106 // pairs included in the response trailer.
107 func ReadResponse(r *bufio.Reader, req *Request) (*Response, error) {
108 tp := textproto.NewReader(r)
113 // Parse the first line of the response.
114 line, err := tp.ReadLine()
117 err = io.ErrUnexpectedEOF
121 f := strings.SplitN(line, " ", 3)
123 return nil, &badStringError{"malformed HTTP response", line}
129 resp.Status = f[1] + " " + reasonPhrase
130 resp.StatusCode, err = strconv.Atoi(f[1])
132 return nil, &badStringError{"malformed HTTP status code", f[1]}
137 if resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {
138 return nil, &badStringError{"malformed HTTP version", resp.Proto}
141 // Parse the response headers.
142 mimeHeader, err := tp.ReadMIMEHeader()
146 resp.Header = Header(mimeHeader)
148 fixPragmaCacheControl(resp.Header)
150 err = readTransfer(resp, r)
158 // RFC2616: Should treat
161 // Cache-Control: no-cache
162 func fixPragmaCacheControl(header Header) {
163 if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" {
164 if _, presentcc := header["Cache-Control"]; !presentcc {
165 header["Cache-Control"] = []string{"no-cache"}
170 // ProtoAtLeast reports whether the HTTP protocol used
171 // in the response is at least major.minor.
172 func (r *Response) ProtoAtLeast(major, minor int) bool {
173 return r.ProtoMajor > major ||
174 r.ProtoMajor == major && r.ProtoMinor >= minor
177 // Writes the response (header, body and trailer) in wire format. This method
178 // consults the following fields of the response:
188 // Header, values for non-canonical keys will have unpredictable behavior
190 // Body is closed after it is sent.
191 func (r *Response) Write(w io.Writer) error {
197 text, ok = statusText[r.StatusCode]
199 text = "status code " + strconv.Itoa(r.StatusCode)
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")
207 // Process Body,ContentLength,Close,Trailer
208 tw, err := newTransferWriter(r)
212 err = tw.WriteHeader(w)
218 err = r.Header.WriteSubset(w, respExcludeHeader)
224 io.WriteString(w, "\r\n")
226 // Write body and trailer
227 err = tw.WriteBody(w)