Home > Backend Development > Golang > Does GoLang\'s `http.DefaultClient.Do(req)` Automatically Retry HTTP Requests on Server Unavailability?

Does GoLang\'s `http.DefaultClient.Do(req)` Automatically Retry HTTP Requests on Server Unavailability?

Patricia Arquette
Release: 2024-10-30 14:34:50
Original
1020 people have browsed it

Does GoLang's `http.DefaultClient.Do(req)` Automatically Retry HTTP Requests on Server Unavailability?

HTTP Request Retry Mechanism

Question:

In GoLang, when executing http.DefaultClient.Do(req), will the HTTP request attempt retries automatically if the server is temporarily unavailable?

Answer:

No, the GoLang HTTP client does not implement automatic retries. You need to implement a custom retry mechanism to handle server unavailability.

Retry Pattern Implementation:

Here's an example of a basic retry pattern you can implement:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<code class="go">package main

 

import (

    "fmt"

    "io/ioutil"

    "log"

    "net/http"

)

 

func main() {

    var (

        err      error

        response *http.Response

        retries  int = 3

    )

 

    for retries > 0 {

        response, err = http.Get("https://non-existent") // Replace with your server URL

 

        if err != nil {

            log.Println("Request failed", err)

            retries -= 1

        } else {

            break // Request succeeded, exit the retry loop

        }

    }

 

    if response != nil {

        defer response.Body.Close()

        data, err := ioutil.ReadAll(response.Body)

        if err != nil {

            log.Fatal(err)

        }

        fmt.Printf("Data received: %s", data)

    } else {

        log.Fatal("Unable to establish connection")

    }

}</code>

Copy after login

In this example, the http.Get request is executed in a loop, attempting to fetch data from the server. If a request fails, the loop decrements the retry count and continues until either all retries are exhausted or the request succeeds. If the request succeeds, the response is printed. If all retries fail, an error message is logged.

The above is the detailed content of Does GoLang\'s `http.DefaultClient.Do(req)` Automatically Retry HTTP Requests on Server Unavailability?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template