Bound outbound HTTP calls
Keep a slow dependency from exhausting request capacity.
Share a client with limits
Create an HTTP client with an appropriate timeout and reuse it instead of constructing a new client for every call. Pass the caller's context into the request so cancellation travels through the service. A timeout should fit inside the incoming request's overall deadline.
Always close the body
After a successful Do call, close the response body, even for an error status. Check the status before decoding. Limit the amount of error-body text you read so an upstream service cannot fill memory with an enormous response.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil { return err }
resp, err := client.Do(req)
if err != nil { return err }
defer resp.Body.Close()
Test a slow upstream
Use a local test server to delay a response and confirm the client returns on deadline. Test a non-2xx status and a malformed success body. For retries, distinguish a safe read from a write that may already have happened. Preserve the underlying error for useful logging.
Check your understanding
Why pass the incoming context to an outbound HTTP request?
Show explanation
It lets the call stop when the user request is canceled or its deadline expires.
You can read for free. Create an account to save your progress.
← Previous lesson: Read database rows safely Next lesson: Retry without multiplying side effects →Put this lesson into practice
A practice activity at this level in the same module.
Try: Fan out with a bounded worker poolFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.