File tree Expand file tree Collapse file tree 2 files changed +29
-0
lines changed
Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -10,6 +10,7 @@ package resty
1010
1111import (
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+
2548func errIsContextCanceled (err error ) bool {
2649 ue , ok := err .(* url.Error )
2750 if ! ok {
Original file line number Diff line number Diff 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()`.
5757func (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.
6871func (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
You can’t perform that action at this time.
0 commit comments