http.Response represents the result of an HTTP round trip. An http.Client sends an http.Request and returns a response whose status code can be inspected and whose Body can be read as a byte stream. section 7.3.1
Process a response by following these practical steps:
- Call Client.Do with an http.Request and check the returned error before using the response. section 7.3.1
- Inspect StatusCode to determine whether the request succeeded. section 7.3.1
- Read Body as a stream, using io.Copy and io.Discard when counting bytes without retaining content. section 7.3.5
- Close Body after processing so the TCP connection can be reused; avoid closing it when Do returns an error because Body may be nil. section 7.3.5
Count downloaded response bytes
func Send(client *http.Client, req *http.Request) Result { resp, err := client.Do(req) if err == nil { defer resp.Body.Close() bytes, err := io.Copy(io.Discard, resp.Body) return Result{Status: resp.StatusCode, Bytes: bytes, Error: err} } return Result{Error: err} } This pattern records the status and transferred byte count while discarding the body. io.Copy reads until the stream ends and does not report io.EOF as an error. section 7.3.5
Figure 7.4 Sending a request to a server using an HTTP client and receiving a response. When we receive a response, we can read its body as a byte stream.
Trace the request-to-response flow from http.Client through the returned Body byte stream. section 7.3.1
