In Go, you can implement HTTP request retry and timeout handling using the net/http
package along with the built-in time
package. Here is an example of how to achieve this:
import (
"net/http"
"time"
"fmt"
)
func sendRequestWithRetryAndTimeout(url string, retries int, timeout time.Duration) (*http.Response, error) {
client := http.Client{
Timeout: timeout,
}
for i := 0; i <= retries; i++ {
resp, err := client.Get(url)
// Retry if the request failed
if err != nil {
fmt.Printf("Request attempt %d failed: %s\n", i, err)
continue
}
// Retry if the response status code is an error
if resp.StatusCode >= 400 {
fmt.Printf("Request attempt %d returned status code: %d\n", i, resp.StatusCode)
resp.Body.Close()
continue
}
// Request succeeded
return resp, nil
}
return nil, fmt.Errorf("maximum retries exceeded")
}
func main() {
url := "https://example.com"
retries := 3
timeout := time.Second * 5
resp, err := sendRequestWithRetryAndTimeout(url, retries, timeout)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Response:", resp.Status)
}
In the above example, the sendRequestWithRetryAndTimeout
function sends an HTTP GET request to the specified URL with the provided number of retries and timeout. It retries the request if there is an error or if the response status code is an error (e.g., 4xx or 5xx). If the maximum number of retries is exceeded, it returns an error.