Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions context18_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package resty

import (
"context"
"net/http"
"net/url"
"testing"
)
Expand All @@ -22,6 +23,28 @@ func TestRequestContext(t *testing.T) {
assertNotNil(t, r.Context())
}

func TestContextWithPreRequestHook(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()

c := dc()
c.SetPreRequestHook(func(cl *Client, r *Request) error {
type ctxKey int
var key ctxKey
val := "test-value"
ctx := context.WithValue(r.Context(), key, val)
r.SetContext(ctx)
ctxValue := r.RawRequest.Context().Value(key).(string)
assertEqual(t, val, ctxValue)
return nil
})

resp, err := c.R().Get(ts.URL)

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
}

func errIsContextCanceled(err error) bool {
ue, ok := err.(*url.Error)
if !ok {
Expand Down
6 changes: 6 additions & 0 deletions request17.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ type Request struct {
// Context method returns the Context if its already set in request
// otherwise it creates new one using `context.Background()`.
func (r *Request) Context() context.Context {
if r.RawRequest != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@clippit I have intentionally did not make these changes. Because by resty design PreRequestHook is only meant to modify RawRequest not resty Request` (refer to #62). Any changes made in resty Request instance will not affect the request.

return r.RawRequest.Context()
}
if r.ctx == nil {
return context.Background()
}
Expand All @@ -67,6 +70,9 @@ func (r *Request) Context() context.Context {
// documentation.
func (r *Request) SetContext(ctx context.Context) *Request {
r.ctx = ctx
if r.RawRequest != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@clippit I have intentionally did not make these changes. Because by resty design PreRequestHook is only meant to modify RawRequest not resty Request` (refer to #62 ). Any changes made in resty Request instance will not affect the request.

r.addContextIfAvailable()
}
return r
}

Expand Down