Skip to content

Commit

Permalink
Add sleep on reconnect functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
IamCathal committed Jul 8, 2020
1 parent d6ef33f commit 2eccb23
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
8 changes: 8 additions & 0 deletions httplib/httplib.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ type BeegoHTTPSettings struct {
Gzip bool
DumpBody bool
Retries int // if set to -1 means will retry forever
RetryDelay time.Duration
}

// BeegoHTTPRequest provides more useful methods for requesting one url than http.Request.
Expand Down Expand Up @@ -202,6 +203,11 @@ func (b *BeegoHTTPRequest) Retries(times int) *BeegoHTTPRequest {
return b
}

func (b *BeegoHTTPRequest) RetryDelay(delay time.Duration) *BeegoHTTPRequest {
b.setting.RetryDelay = delay
return b
}

// DumpBody setting whether need to Dump the Body.
func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
b.setting.DumpBody = isdump
Expand Down Expand Up @@ -512,11 +518,13 @@ func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
// retries default value is 0, it will run once.
// retries equal to -1, it will run forever until success
// retries is setted, it will retries fixed times.
// Sleeps for a 400ms inbetween calls to reduce spam
for i := 0; b.setting.Retries == -1 || i <= b.setting.Retries; i++ {
resp, err = client.Do(b.req)
if err == nil {
break
}
time.Sleep(b.setting.RetryDelay)
}
return resp, err
}
Expand Down
29 changes: 29 additions & 0 deletions httplib/httplib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package httplib

import (
"errors"
"io/ioutil"
"net"
"net/http"
Expand All @@ -33,6 +34,34 @@ func TestResponse(t *testing.T) {
t.Log(resp)
}

func TestDoRequest(t *testing.T) {
req := Get("https://goolnk.com/33BD2j")
retryAmount := 1
req.Retries(1)
req.RetryDelay(1400 * time.Millisecond)
retryDelay := 1400 * time.Millisecond

req.setting.CheckRedirect = func(redirectReq *http.Request, redirectVia []*http.Request) error {
return errors.New("Redirect triggered")
}

startTime := time.Now().UnixNano() / int64(time.Millisecond)

_, err := req.Response()
if err == nil {
t.Fatal("Response should have yielded an error")
}

endTime := time.Now().UnixNano() / int64(time.Millisecond)
elapsedTime := endTime - startTime
delayedTime := int64(retryAmount) * retryDelay.Milliseconds()

if elapsedTime < delayedTime {
t.Errorf("Not enough retries. Took %dms. Delay was meant to take %dms", elapsedTime, delayedTime)
}

}

func TestGet(t *testing.T) {
req := Get("http://httpbin.org/get")
b, err := req.Bytes()
Expand Down

0 comments on commit 2eccb23

Please sign in to comment.