mirror of
https://github.com/astaxie/beego.git
synced 2024-11-21 23:20:54 +00:00
Add sleep on reconnect functionality
This commit is contained in:
parent
d6ef33feee
commit
2eccb23461
@ -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.
|
||||
@ -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
|
||||
@ -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
|
||||
}
|
||||
|
@ -15,6 +15,7 @@
|
||||
package httplib
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
@ -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()
|
||||
|
Loading…
Reference in New Issue
Block a user