Cookies management by TermsFeed Cookie Consent

โฐ Handle HTTP timeout error in Go

shorts http

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
    "log"
    "net/http"
    "os"
    "time"
)

func main() {
    httpClient := http.Client{Timeout: 1 * time.Nanosecond}

    req, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
    if err != nil {
        log.Fatal(err)
    }

    _, err = httpClient.Do(req)
    if os.IsTimeout(err) {
        log.Printf("timeout error: %v\n", err)
    }
}

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.


Thank you for being on our site ๐Ÿ˜Š. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

๐Ÿงช Write end-to-end tests in Go using httptest.Server

shorts httptest http testing

โฑ๏ธ Set HTTP client timeout in Go

Learn how to set a time limit for the execution of an HTTP request
http

๐Ÿพ How to compare strings in Go

shorts introduction strings