liveBook · Manning

Http.Response

As explained in Go by Example

http.Response is the Go standard-library type representing an HTTP response, including its status, headers, and body.

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.
A diagram of a diagram

AI-generated content may be incorrect.

Trace the request-to-response flow from http.Client through the returned Body byte stream. section 7.3.1

How Go by Example covers it

How deep it goes
Explains request execution, status inspection, streaming reads, connection reuse, closure, and io.EOF behavior.
Examples
Uses Client.Do, StatusCode checks, a Send function, io.Copy, Body.Close, and ResponseRecorder-based handler tests.
What it assumes
Assumes basic HTTP requests and Go errors, while teaching client round trips and generic I/O streams.
What you can do after
Apply it via net/http to inspect statuses, stream bodies, count transferred bytes, and release response resources.
How it connects
Connects http.Client, http.Request, HTTP round trips, io.Copy, io.Discard, and TCP connection reuse.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.