Skip to content

Commit

Permalink
Preserve request body state when retrying
Browse files Browse the repository at this point in the history
When POST request was retried it threw a „Body length 0“ error. See janeczku/docker-machine-vultr#26

Signed-off-by: janeczku <jan@rancher.com>
  • Loading branch information
janeczku committed Jul 4, 2017
1 parent 253a352 commit 8cb6b59
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lib

import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
Expand Down Expand Up @@ -168,8 +169,25 @@ func (c *Client) do(req *http.Request, data interface{}) error {
// Throttle http requests to avoid hitting Vultr's API rate-limit
c.bucket.Wait(1)

// Request body gets drained on each read so we
// need to save it's content for retrying requests
var err error
var requestBody []byte
if req.Body != nil {
requestBody, err = ioutil.ReadAll(req.Body)
if err != nil {
return fmt.Errorf("Error reading request body: %v", err)
}
req.Body.Close()
}

var apiError error
for tryCount := 1; tryCount <= c.MaxAttempts; tryCount++ {
// Restore request body to the original state
if requestBody != nil {
req.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
}

resp, err := c.client.Do(req)
if err != nil {
return err
Expand Down
24 changes: 24 additions & 0 deletions lib/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,27 @@ func Test_Client_Retry(t *testing.T) {

wg.Wait()
}

// Test that body state is preserved when retrying POST requests
func Test_Client_Retry_Post(t *testing.T) {
server := getTestServerThrottled(`{"SUBID":"5671234"}`)
defer server.Close()

options := Options{
Endpoint: server.URL,
MaxRetries: 5,
}
client := NewClient("test-key", &options)

var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
_, err := client.CreateBlockStorage("delta", 33, 150)
assert.NoError(t, err)
}()
}

wg.Wait()
}

0 comments on commit 8cb6b59

Please # to comment.