Skip to content

Commit 82efb93

Browse files
committed
retry sending request if server is gone
1 parent 39c487f commit 82efb93

File tree

1 file changed

+28
-20
lines changed

1 file changed

+28
-20
lines changed

api.go

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -91,31 +91,39 @@ func (a *API) DoRequest(method, path string, body, unmarshalResInto interface{})
9191
req.Header.Add("Authorization", a.authHeaderValue)
9292
}
9393

94-
res, err := http.DefaultClient.Do(req)
95-
if err != nil {
96-
return err
97-
}
98-
99-
resBody, err := ioutil.ReadAll(res.Body)
100-
if err != nil {
101-
return err
102-
}
94+
attempt := 0
95+
for {
96+
res, err := http.DefaultClient.Do(req)
97+
if err != nil {
98+
attempt++
99+
if attempt > 3 {
100+
return fmt.Errorf("%s, retried 4 times", err.Error())
101+
}
102+
time.Sleep(time.Second * time.Duration(attempt) * 2)
103+
continue
104+
}
103105

104-
if res.StatusCode >= 400 && res.StatusCode < 600 {
105-
errorRes := struct {
106-
Error string `json:"error"`
107-
}{}
108-
err = json.Unmarshal(resBody, &errorRes)
106+
resBody, err := ioutil.ReadAll(res.Body)
109107
if err != nil {
110-
return fmt.Errorf("server returned %d code, with body %s", res.StatusCode, string(resBody))
108+
return err
109+
}
110+
111+
if res.StatusCode >= 400 && res.StatusCode < 600 {
112+
errorRes := struct {
113+
Error string `json:"error"`
114+
}{}
115+
err = json.Unmarshal(resBody, &errorRes)
116+
if err != nil {
117+
return fmt.Errorf("server returned %d code, with body %s", res.StatusCode, string(resBody))
118+
}
119+
return errors.New(errorRes.Error)
111120
}
112-
return errors.New(errorRes.Error)
113-
}
114121

115-
if unmarshalResInto != nil {
116-
return json.Unmarshal(resBody, unmarshalResInto)
122+
if unmarshalResInto != nil {
123+
return json.Unmarshal(resBody, unmarshalResInto)
124+
}
125+
return nil
117126
}
118-
return nil
119127
}
120128

121129
// NoCredentials returns true if the SetCredentials method was not yet called and we aren't in mock mode

0 commit comments

Comments
 (0)