Skip to content

Commit

Permalink
maintain request body across client retries
Browse files Browse the repository at this point in the history
  • Loading branch information
mhupman committed Jan 27, 2016
1 parent 1d5e53f commit e83d435
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
9 changes: 9 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,20 @@ func (c *Client) DoRequestJSON(method string, path string, obj interface{}, v in
}

func (c *Client) Do(req *http.Request, v interface{}) error {
// drain and cache the request body
originalRequestBody, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}

var resultError error
for attempt := 0; attempt <= c.retryAttempts; attempt++ {
resultError = nil
time.Sleep(DefaultBackoffPolicy.Duration(attempt))

// Rehydrate the request body since it might have been drained by the previous attempt
req.Body = ioutil.NopCloser(bytes.NewBuffer(originalRequestBody))

if c.ShowRequest {
fmt.Printf("%+v\n", req)
}
Expand Down
34 changes: 31 additions & 3 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package yext

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strings"
"testing"
)
Expand Down Expand Up @@ -40,7 +43,7 @@ func TestRetries(t *testing.T) {
w.WriteHeader(http.StatusInternalServerError)
})

client.DoRequest("", "", nil)
client.DoRequest("GET", "", nil)

if requests != 4 {
t.Error("Expected 4 net attempts when error encountered, only got", requests)
Expand All @@ -64,7 +67,7 @@ func TestLastRetryError(t *testing.T) {
w.Write([]byte(errf(request)))
})

err := client.DoRequest("", "", nil)
err := client.DoRequest("GET", "", nil)

expectedErr := errf(client.retryAttempts + 1)
if !strings.Contains(err.Error(), expectedErr) {
Expand All @@ -90,9 +93,34 @@ func TestBailout(t *testing.T) {

})

err := client.DoRequest("", "", nil)
err := client.DoRequest("GET", "", nil)

if err != nil {
t.Error("Expected error to be nil when final attempt succeeded:", err)
}
}

func TestRetryWithBody(t *testing.T) {
setup()
client.retryAttempts = 3
defer teardown()

requests := 0
body := map[string]interface{}{"foo": "bar"}

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
requests++

b, _ := ioutil.ReadAll(r.Body)
var payload map[string]interface{}
json.Unmarshal(b, &payload)
if !reflect.DeepEqual(body, payload) {
t.Error("Expected to get identical body in retry scenario, got", string(b), "instead")
}

// Force retries
w.WriteHeader(http.StatusInternalServerError)
})

client.DoRequestJSON("POST", "", body, nil)
}

0 comments on commit e83d435

Please sign in to comment.