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
I found a way to do this without re-creating the request every time. here's a sample code, which is a very slight modification of @Cerise Limón and is similar to @Rambo's code in that it creates the request only once:
func Post(URL string, data *bytes.Buffer, cl *http.Client) ([]byte, error) {
var err error
req, err := http.NewRequest("POST", URL, ioutil.NopCloser(data))
if err != nil {
log.Errorf("Unable to create the request: %v", err)
return nil, err
}
req.Header.Set("User-Agent", ua)
for i := 0; i < 10; i++ {
rsp, err := cl.Do(req)
if err == nil && rsp.StatusCode == 200 {
defer rsp.Body.Close()
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
fmt.Printf("Error: %v", err)
return nil, err
}
return b, nil
}
log.Errorf("Proxy is slow or down %v", err)
time.Sleep(1 * time.Second)
}
return nil, fmt.Errorf("after 10 tries error: %v", err)
}
func main() {
client := http.Client{}
data := []byte{0, 1, 2, 3, 4}
Post("http://server/my/api/resource/", bytes.NewBuffer(data), &client)
}