Read and close HTTP response bodies
Read and close HTTP response bodies
When Client.Do succeeds, the caller owns Response.Body and must close it, including on non-success HTTP statuses. The body implements io.ReadCloser. Reading to EOF and closing can allow HTTP/1.x connection reuse. For untrusted or large bodies, cap reads or stream into a bounded destination instead of blindly allocating all bytes.
package main
import ( "errors" "fmt" "io" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func readBounded(r io.Reader, max int64) ([]byte, error) { b, e := io.ReadAll(io.LimitReader(r, max+1)) if e != nil { return nil, e } if int64(len(b)) > max { return nil, errors.New("body too large") } return b, nil}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }) defer s.Close() res, e := c.Get(s.URL) check(e) defer res.Body.Close() b, e := readBounded(res.Body, 5) check(e) fmt.Println(string(b))}LimitReader exposes at most max+1 bytes, so a body exactly at the limit is accepted and an extra byte detects oversize. This helper assumes a small nonnegative configured max far below MaxInt64; validate arbitrary limit inputs first. It propagates read errors, including truncation. Close is deferred only after checking the request error.
Expected output:
helloReject oversize instead of silently truncating
package main
import ( "errors" "fmt" "io" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func readBounded(r io.Reader, max int64) ([]byte, error) { b, e := io.ReadAll(io.LimitReader(r, max+1)) if e != nil { return nil, e } if int64(len(b)) > max { return nil, errors.New("body too large") } return b, nil}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "abcdef") }) defer s.Close() res, e := c.Get(s.URL) check(e) defer res.Body.Close() _, e = readBounded(res.Body, 5) fmt.Println(e)}Do not drain an unlimited response merely to save a connection: closing early may discard a connection but protects resources. Content-Length may be unknown and is not sufficient as the only size check. For downloads, check copy errors, limit total bytes and clean up partial files. In loops close per iteration rather than deferring every close until the outer function returns.
Expected output:
body too largeTry it locally
Use readBounded on a local response "1234" with limit 3; print whether an error occurred.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 03: Read and close HTTP response bodies
Check the lesson objective before moving on.
Who closes a successful Do response body?
Why read limit+1 bytes?