Skip to content

Commit 708c175

Browse files
committed
point to the same context after http.Request created
1 parent 63ac674 commit 708c175

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

context18_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ package resty
1010

1111
import (
1212
"context"
13+
"net/http"
1314
"net/url"
1415
"testing"
1516
)
@@ -22,6 +23,28 @@ func TestRequestContext(t *testing.T) {
2223
assertNotNil(t, r.Context())
2324
}
2425

26+
func TestContextWithPreRequestHook(t *testing.T) {
27+
ts := createGetServer(t)
28+
defer ts.Close()
29+
30+
c := dc()
31+
c.SetPreRequestHook(func(cl *Client, r *Request) error {
32+
type ctxKey int
33+
var key ctxKey
34+
val := "test-value"
35+
ctx := context.WithValue(r.Context(), key, val)
36+
r.SetContext(ctx)
37+
ctxValue := r.RawRequest.Context().Value(key).(string)
38+
assertEqual(t, val, ctxValue)
39+
return nil
40+
})
41+
42+
resp, err := c.R().Get(ts.URL)
43+
44+
assertError(t, err)
45+
assertEqual(t, http.StatusOK, resp.StatusCode())
46+
}
47+
2548
func errIsContextCanceled(err error) bool {
2649
ue, ok := err.(*url.Error)
2750
if !ok {

request17.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ type Request struct {
5555
// Context method returns the Context if its already set in request
5656
// otherwise it creates new one using `context.Background()`.
5757
func (r *Request) Context() context.Context {
58+
if r.RawRequest != nil {
59+
return r.RawRequest.Context()
60+
}
5861
if r.ctx == nil {
5962
return context.Background()
6063
}
@@ -67,6 +70,9 @@ func (r *Request) Context() context.Context {
6770
// documentation.
6871
func (r *Request) SetContext(ctx context.Context) *Request {
6972
r.ctx = ctx
73+
if r.RawRequest != nil {
74+
r.addContextIfAvailable()
75+
}
7076
return r
7177
}
7278

0 commit comments

Comments
 (0)