Automatic Retry in HTTP Requests
Question:
In GoLang, while attempting to push data to an Apache server, the server may be temporarily unavailable. Will the HTTP request automatically retry in such a scenario?
Answer:
No, the default HTTP client in GoLang does not automatically retry HTTP requests.
Implementation of Retry Method:
To implement a custom retry mechanism, consider the following example:
<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") if err != nil { log.Println(err) retries -= 1 } 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>
This code demonstrates a basic retry mechanism, allowing for a maximum of three retries before failing. The HTTP request is repeatedly issued until it succeeds or the specified number of retries has been exhausted.
The above is the detailed content of Does GoLang\'s default HTTP client automatically retry requests when the server is unavailable?. For more information, please follow other related articles on the PHP Chinese website!