Skip to content

Commit

Permalink
Bugfix: context prematurely canceled
Browse files Browse the repository at this point in the history
Request contexts may be prematurely canceled due to the cancel
function being immediately called after sending the request rather
then being deferred.
  • Loading branch information
ido50 committed Jun 4, 2024
1 parent 3cd280d commit 4fe58d7
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -891,7 +891,9 @@ func (req *HTTPRequest) RunContext(ctx context.Context) error {
return err
}

cancel()
if cancel != nil {
defer cancel()
}

// make sure to read the entire body and close the request once we're
// done, this is important in order to reuse connections and prevent
Expand Down Expand Up @@ -924,8 +926,11 @@ func (req *HTTPRequest) Subscribe(ctx context.Context, messages chan []byte) err
}

go func() {
if cancel != nil {
defer cancel()
}

defer closeBody(res.Body)
defer cancel()

br := bufio.NewReader(res.Body)

Expand Down Expand Up @@ -991,10 +996,10 @@ func (req *HTTPRequest) execute(ctx context.Context) (
res, err = req.cli.retryRequest(ctx, req.logger, r, &req.bodyDst, attempts)
if err != nil {
if errors.Is(err, ErrTimeoutReached) {
return nil, nil, err
return nil, cancel, err
}

return nil, nil, fmt.Errorf("request failed: %w", err)
return nil, cancel, fmt.Errorf("request failed: %w", err)
}

return res, cancel, nil
Expand Down

0 comments on commit 4fe58d7

Please sign in to comment.