[go: nahoru, domu]

Skip to content

Commit

Permalink
WithContext should return a new Request
Browse files Browse the repository at this point in the history
The method should not mutate the original object. That is how the method from stdlib works.
  • Loading branch information
ash2k committed Sep 6, 2021
1 parent 02c1586 commit bced3ed
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
6 changes: 4 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,10 @@ type Request struct {
// WithContext returns wrapped Request with a shallow copy of underlying *http.Request
// with its context changed to ctx. The provided ctx must be non-nil.
func (r *Request) WithContext(ctx context.Context) *Request {
r.Request = r.Request.WithContext(ctx)
return r
return &Request{
body: r.body,
Request: r.Request.WithContext(ctx),
}
}

// BodyBytes allows accessing the request body. It is an analogue to
Expand Down
9 changes: 6 additions & 3 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,18 +468,21 @@ func TestClient_RequestWithContext(t *testing.T) {
t.Fatalf("err: %v", err)
}
ctx, cancel := context.WithCancel(req.Request.Context())
req = req.WithContext(ctx)
reqCtx := req.WithContext(ctx)
if reqCtx == req {
t.Fatal("WithContext must return a new Request object")
}

client := NewClient()

called := 0
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
called++
return DefaultRetryPolicy(req.Request.Context(), resp, err)
return DefaultRetryPolicy(reqCtx.Request.Context(), resp, err)
}

cancel()
_, err = client.Do(req)
_, err = client.Do(reqCtx)

if called != 1 {
t.Fatalf("CheckRetry called %d times, expected 1", called)
Expand Down

0 comments on commit bced3ed

Please sign in to comment.