Eddie Flores

Product Development & Engineering

Making External Requests the Right Way

One of the main gotchas when making an external request is relying on the default HTTP client to do it. The danger happens when the external server fails to respond, causing your service to hang indefinitely.

Solution

When making external requests, avoid the default HTTP client. Define a http.Client of your own or use Request.WithContext.

Examples

Configuring a client to use a 15 second timeout.

client := &http.Client {
  Timeout: 15 * Time.Second,
}
resp, err := client.Get(...)

Using an empty context and Request.WithContext.

ctx := context.WithTimeout(context.Background(), 15 * time.Second)
req, err := http.NewRequest(...)
if err != nil {
  return err
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))