Friday, December 6, 2024
HomeGolangDeal with HTTP timeout error in Go (Golang)

Deal with HTTP timeout error in Go (Golang)



To deal with an HTTP timeout error in Go, use the os.IsTimeout() operate from the built-in os bundle. It returns true if the request time restrict has been exceeded or false in any other case.

Instance

Within the instance, we create an HTTP shopper with a timeout of 1 nanosecond. With such a brief timeout, we are able to make sure that we’ll obtain a timeout error after we ship a request to the https://instance.com server.

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

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

func fundamental() {
    httpClient := http.Shopper{Timeout: 1 * time.Nanosecond}

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

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

Output:

2022/08/28 18:35:48 timeout error: Get "https://instance.com": context deadline exceeded (Shopper.Timeout exceeded whereas awaiting headers)

Learn this text to be taught extra concerning the context deadline exceeded, which can also be a timeout error.

To be sure that os.IsTimeout() works accurately, change the timeout worth in line 11 to 1 * time.Minute. If there may be at present no drawback with https://instance.com, the request will probably be processed throughout the time restrict of 1 minute and you’ll not see any error on the output.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments