To handle an HTTP timeout error in Go, use the os.IsTimeout()
function from the built-in os
package. It returns true
if the request time limit has been exceeded or false
otherwise.
Example
In the example, we create an HTTP client with a timeout of 1 nanosecond. With such a short timeout, we can be sure that we will receive a timeout error when we send a request to the https://example.com
server.
|
|
Output:
2022/08/28 18:35:48 timeout error: Get "https://example.com": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
Read this article to learn more about the
context deadline exceeded
, which is also a timeout error.
To make sure that os.IsTimeout()
works correctly, change the timeout value in line 11
to 1 * time.Minute
. If there is currently no problem with https://example.com
, the request will be processed within the time limit of 1 minute and you will not see any error on the output.