Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve request body state when retrying #39

Merged
merged 1 commit into from
Jul 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}