I\'m trying to retry a request if there is a connection/proxy error. For some reasons I keep getting this error which doesn\'t seem to recover regardless the attepts to retry th
The problem is that the request body is read to the end on the first call to Do(). On subsequent calls to Do(), no data is read from the response body.
The fix is to move the creation of the body reader inside the for loop. This requires that the request also be created inside the for loop.
func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
body := form.Encode()
for i := 0; i < 10; i++ {
req, err := http.NewRequest("POST", URL, strings.NewReader(body))
if err != nil {
log.Error(err)
return nil, err
}
req.Header.Set("User-Agent", ua)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rsp, err := cl.Do(req)
if err == nil {
defer rsp.Body.Close()
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
log.Error(err)
return nil, err
}
return b, nil
}
if !IsErrorProxy(err) {
return nil, err
}
log.Errorf("Proxy is slow or down ")
time.Sleep(6 * time.Second)
}
return nil, fmt.Errorf("after 10 tries error: %v", err)
}