user2433953
user2433953

Reputation: 131

Does the http request automatically retry?

I am trying to push my data to apache server using GoLang. Suppose my apache server is temporarily stopped. Then will my http request retry automatically. I am using this statement

resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return errors.Wrap(err, "http request error")
    }

I am unable to proceed further coz what is think is my execution is stuck here. And I am repeatedly getting this error.

Upvotes: 11

Views: 32579

Answers (2)

nishith
nishith

Reputation: 1283

You can use more cleaner implementation of retrying by using retryablehttp https://github.com/hashicorp/go-retryablehttp which handles most of the conditions
This is provides customisation for retry policy, backoffs etc.

Upvotes: 15

nbari
nbari

Reputation: 26955

No, you will need to implement your own retry method, this is a basic example that could give you an idea:

https://play.golang.org/p/_o5AgePDEXq

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")
        // response, err = http.Get("https://google.com/robots.txt")
        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)
    }
}

Upvotes: 16

Related Questions