Skip to content

Commit fe7ae0c

Browse files
committed
Added context levigross#33
Signed-off-by: Levi Gross <[email protected]>
1 parent 730bf25 commit fe7ae0c

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

base_get_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package grequests
22

33
import (
44
"bytes"
5+
"context"
56
"encoding/json"
67
"encoding/xml"
78
"errors"
@@ -1234,6 +1235,16 @@ func TestGetCustomRequestTimeout(t *testing.T) {
12341235
}
12351236
}
12361237

1238+
func TestGetCustomRequestTimeoutContext(t *testing.T) {
1239+
derContext := context.Background()
1240+
ctx, cancel := context.WithTimeout(derContext, time.Microsecond)
1241+
ro := &RequestOptions{Context: ctx}
1242+
cancel()
1243+
if _, err := Get("http://httpbin.org", ro); err == nil {
1244+
t.Error("unexpected: successful connection")
1245+
}
1246+
}
1247+
12371248
// verifyResponse will verify the following conditions
12381249
// 1. The request didn't return an error
12391250
// 2. The response returned an OK (a status code within the 200 range)

request.go

+9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import (
1919

2020
"github.com/google/go-querystring/query"
2121

22+
"context"
23+
2224
"golang.org/x/net/publicsuffix"
2325
)
2426

@@ -123,6 +125,9 @@ type RequestOptions struct {
123125
// CookieJar allows you to specify a special cookiejar to use with your request.
124126
// this option will take precedence over the `UseCookieJar` option above.
125127
CookieJar http.CookieJar
128+
129+
// Context can be used to maintain state between requests https://golang.org/pkg/context/#Context
130+
Context context.Context
126131
}
127132

128133
func doRegularRequest(requestVerb, url string, ro *RequestOptions) (*Response, error) {
@@ -174,6 +179,10 @@ func buildRequest(httpMethod, url string, ro *RequestOptions, httpClient *http.C
174179

175180
addRedirectFunctionality(httpClient, ro)
176181

182+
if ro.Context != nil {
183+
req = req.WithContext(ro.Context)
184+
}
185+
177186
return httpClient.Do(req)
178187
}
179188

0 commit comments

Comments
 (0)