Sobes.tech
Junior — Middle

How can a timeout for waiting for a response be set when making an HTTP request?

sobes.tech AI

Answer from AI

In Go, to set a timeout for an HTTP response, you typically use a context with a timeout or configure timeouts in http.Client.

Example with context:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
if err != nil {
    // handle error
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    // handle error, e.g., timeout
}
// process resp

You can also set timeouts directly in http.Client:

client := &http.Client{
    Timeout: 5 * time.Second, // total timeout for the request
}
resp, err := client.Get("https://example.com")

This way, if the server does not respond within the specified time, the request will be canceled with a timeout error.