Home > Article > Backend Development > 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:
<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>
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!