Skip to content
This repository was archived by the owner on Jan 15, 2024. It is now read-only.

Commit 3e5bd17

Browse files
committed
Read request body on first try
Even if successful by always reading the body we can make certain that the body will be sent to the server, even if the request fails before reading the body. See parent commit for further reference. Signed-off-by: Leandro López (inkel) <leandro.lopez@grafana.com>
1 parent 4d9aeb6 commit 3e5bd17

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

client.go

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -71,28 +71,22 @@ func (c Client) WithOrgID(orgID int64) *Client {
7171
return &c
7272
}
7373

74-
func (c *Client) request(method, requestPath string, query url.Values, body io.Reader, responseStruct interface{}) error {
74+
func (c *Client) request(method, requestPath string, query url.Values, bodyRd io.Reader, responseStruct interface{}) error {
7575
var (
7676
req *http.Request
7777
resp *http.Response
7878
err error
7979
bodyContents []byte
8080
)
8181

82-
// If we want to retry a request that sends data, we'll need to stash the request data in memory. Otherwise, we lose it since readers cannot be replayed.
83-
var bodyBuffer bytes.Buffer
84-
if c.config.NumRetries > 0 && body != nil {
85-
body = io.TeeReader(body, &bodyBuffer)
82+
body, err := io.ReadAll(bodyRd)
83+
if err != nil {
84+
return fmt.Errorf("cannot read request body: %w", err)
8685
}
8786

8887
// retry logic
8988
for n := 0; n <= c.config.NumRetries; n++ {
90-
// If it's not the first request, re-use the request body we stashed earlier.
91-
if n > 0 {
92-
body = bytes.NewReader(bodyBuffer.Bytes())
93-
}
94-
95-
req, err = c.newRequest(method, requestPath, query, body)
89+
req, err = c.newRequest(method, requestPath, query, bytes.NewReader(body))
9690
if err != nil {
9791
return err
9892
}

0 commit comments

Comments
 (0)