Home >Backend Development >Golang >How to Retry Failed HTTP Requests in Go?
Retrying Failed HTTP Requests in Go
When attempting to push data to an Apache server using GoLang and encountering an error, it's crucial to consider whether the HTTP request will automatically retry. The response to this question is negative, meaning you must implement a custom retry mechanism.
In the code provided, you're using the http.DefaultClient.Do method to execute the request. This method does not automatically handle retries in case of server unavailability or other errors. To incorporate retry logic, you can adopt a custom approach as demonstrated in the following example:
<code class="go">package main import ( "fmt" "io/ioutil" "log" "net/http" "time" ) func main() { var ( err error response *http.Response retries int = 3 ) for retries > 0 { response, err = http.Get("https://non-existent") // Change the URL to "https://google.com/robots.txt" for testing if err != nil { log.Println(err) time.Sleep(2 * time.Second) // Introduce a delay between retries retries -= 1 continue } else { break } } if response != nil { defer response.Body.Close() data, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } fmt.Printf("data = %s\n", data) } }</code>
In this example, the time.Sleep function has been used to introduce a delay between retries. You can adjust the delay based on the specific requirements of your application. Remember to handle any exceptions or errors that may occur during the retry process, ensuring the stability and reliability of your data transfer.
The above is the detailed content of How to Retry Failed HTTP Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!