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.
18 var respExcludeHeader = map[string]bool{
19 "Content-Length": true,
20 "Transfer-Encoding": true,
24 // Response represents the response from an HTTP request.
26 type Response struct {
27 Status string // e.g. "200 OK"
28 StatusCode int // e.g. 200
29 Proto string // e.g. "HTTP/1.0"
30 ProtoMajor int // e.g. 1
31 ProtoMinor int // e.g. 0
33 // Header maps header keys to values. If the response had multiple
34 // headers with the same key, they will be concatenated, with comma
35 // delimiters. (Section 4.2 of RFC 2616 requires that multiple headers
36 // be semantically equivalent to a comma-delimited sequence.) Values
37 // duplicated by other fields in this struct (e.g., ContentLength) are
38 // omitted from Header.
40 // Keys in the map are canonicalized (see CanonicalHeaderKey).
43 // Body represents the response body.
46 // ContentLength records the length of the associated content. The
47 // value -1 indicates that the length is unknown. Unless RequestMethod
48 // is "HEAD", values >= 0 indicate that the given number of bytes may
52 // Contains transfer encodings from outer-most to inner-most. Value is
53 // nil, means that "identity" encoding is used.
54 TransferEncoding []string
56 // Close records whether the header directed that the connection be
57 // closed after reading Body. The value is advice for clients: neither
58 // ReadResponse nor Response.Write ever closes a connection.
61 // Trailer maps trailer keys to values, in the same
62 // format as the header.
65 // The Request that was sent to obtain this Response.
66 // Request's Body is nil (having already been consumed).
67 // This is only populated for Client requests.
71 // Cookies parses and returns the cookies set in the Set-Cookie headers.
72 func (r *Response) Cookies() []*Cookie {
73 return readSetCookies(r.Header)
76 // ReadResponse reads and returns an HTTP response from r. The
77 // req parameter specifies the Request that corresponds to
78 // this Response. Clients must call resp.Body.Close when finished
79 // reading resp.Body. After that call, clients can inspect
80 // resp.Trailer to find key/value pairs included in the response
82 func ReadResponse(r *bufio.Reader, req *Request) (resp *Response, err os.Error) {
84 tp := textproto.NewReader(r)
88 resp.Request.Method = strings.ToUpper(resp.Request.Method)
90 // Parse the first line of the response.
91 line, err := tp.ReadLine()
94 err = io.ErrUnexpectedEOF
98 f := strings.SplitN(line, " ", 3)
100 return nil, &badStringError{"malformed HTTP response", line}
106 resp.Status = f[1] + " " + reasonPhrase
107 resp.StatusCode, err = strconv.Atoi(f[1])
109 return nil, &badStringError{"malformed HTTP status code", f[1]}
114 if resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {
115 return nil, &badStringError{"malformed HTTP version", resp.Proto}
118 // Parse the response headers.
119 mimeHeader, err := tp.ReadMIMEHeader()
123 resp.Header = Header(mimeHeader)
125 fixPragmaCacheControl(resp.Header)
127 err = readTransfer(resp, r)
135 // RFC2616: Should treat
138 // Cache-Control: no-cache
139 func fixPragmaCacheControl(header Header) {
140 if hp, ok := header["Pragma"]; ok && len(hp) > 0 && hp[0] == "no-cache" {
141 if _, presentcc := header["Cache-Control"]; !presentcc {
142 header["Cache-Control"] = []string{"no-cache"}
147 // ProtoAtLeast returns whether the HTTP protocol used
148 // in the response is at least major.minor.
149 func (r *Response) ProtoAtLeast(major, minor int) bool {
150 return r.ProtoMajor > major ||
151 r.ProtoMajor == major && r.ProtoMinor >= minor
154 // Writes the response (header, body and trailer) in wire format. This method
155 // consults the following fields of resp:
165 // Header, values for non-canonical keys will have unpredictable behavior
167 func (resp *Response) Write(w io.Writer) os.Error {
169 // RequestMethod should be upper-case
170 if resp.Request != nil {
171 resp.Request.Method = strings.ToUpper(resp.Request.Method)
178 text, ok = statusText[resp.StatusCode]
180 text = "status code " + strconv.Itoa(resp.StatusCode)
183 io.WriteString(w, "HTTP/"+strconv.Itoa(resp.ProtoMajor)+".")
184 io.WriteString(w, strconv.Itoa(resp.ProtoMinor)+" ")
185 io.WriteString(w, strconv.Itoa(resp.StatusCode)+" "+text+"\r\n")
187 // Process Body,ContentLength,Close,Trailer
188 tw, err := newTransferWriter(resp)
192 err = tw.WriteHeader(w)
198 err = resp.Header.WriteSubset(w, respExcludeHeader)
204 io.WriteString(w, "\r\n")
206 // Write body and trailer
207 err = tw.WriteBody(w)