Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the http request automatically retry?

Tags:

http

go

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.

like image 960
user2433953 Avatar asked Jun 04 '18 08:06

user2433953


People also ask

What HTTP errors to retry on?

HTTP status codes and the error message can give you a clue. In general, a 5xx status code can be retried, a 4xx status code should be checked first, and a 3xx or 2xx code does not need retried.

How does HTTP GET request work?

An HTTP request is made by a client, to a named host, which is located on a server. The aim of the request is to access a resource on the server. To make the request, the client uses components of a URL (Uniform Resource Locator), which includes the information needed to access the resource.

Is retry-after seconds or milliseconds?

Expected / Desired Behavior / Question From what I could gather on the Net, the "Retry-After" value is specified in seconds, but the pnp code uses this value directly in the setTimeout method (milliseconds).

How long should HTTP requests take?

Statistical analysis of page load speed data collected using the Navigation Timing API shows that an HTTP request can be reasonably approximated to 0.5 seconds.


2 Answers

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)
    }
}
like image 152
nbari Avatar answered Oct 17 '22 02:10

nbari


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.

like image 12
nishith Avatar answered Oct 17 '22 00:10

nishith