Understand the contract
An HTTP client request can fail at the transport layer or receive an HTTP error response. client.Get reports network and protocol failures through error; a 404 or 500 normally arrives as a response with no transport error. Inspect StatusCode before treating the body as successful data.
Create a client with a timeout and reuse it for multiple requests. After a successful request call, close resp.Body on every response path. A bounded read keeps an unexpectedly large reply from consuming unlimited memory. Reading one extra byte lets you detect and reject a body larger than your limit.
Work through the example
Start the server from the previous lesson before running this client in another directory. It requests /hello, accepts a 2xx response and prints the body. The 1 KiB limit fits this greeting exercise. Larger real responses need a format-specific size policy or streaming processing.
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func run() error {
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get("http://127.0.0.1:8080/hello")
if err != nil { return err }
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
const limit = 1024
data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
if err != nil { return err }
if len(data) > limit { return fmt.Errorf("response exceeds %d bytes", limit) }
fmt.Print(string(data))
return nil
}
func main() { if err := run(); err != nil { fmt.Println(err) } }Watch this boundary
Closing a body without reading it completely can prevent connection reuse, depending on the protocol and transport. Do not drain an untrusted unlimited body solely to preserve reuse. Correctness, bounds and cancellation come first; make any reuse optimization explicit and measured.
Practice with a changed input
Call an unknown path and confirm that status checking handles 404. Stop the server to inspect the transport error, then reduce the size limit to trigger the oversized-response branch.
Lesson 40 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services