Skip to content

Commit 054751d

Browse files
committed
Added custom HTTP client capability
Signed-off-by: Levi Gross <[email protected]>
1 parent b7ca8df commit 054751d

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

base.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Package grequests implements a friendly API over Go's existing net/http library
2-
package grequests // import "github.com/levigross/grequests"
2+
package grequests
33

44
// Get takes 2 parameters and returns a Response Struct. These two options are:
55
// 1. A URL

base_get_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,12 @@ func TestGetNoOptions(t *testing.T) {
9898
verifyOkResponse(resp, t)
9999
}
100100

101+
func TestGetNoOptionsCustomClient(t *testing.T) {
102+
resp, _ := Get("http://httpbin.org/get",
103+
&RequestOptions{HTTPClient: http.DefaultClient})
104+
verifyOkResponse(resp, t)
105+
}
106+
101107
func TestGetCustomTLSHandshakeTimeout(t *testing.T) {
102108
ro := &RequestOptions{TLSHandshakeTimeout: 10 * time.Millisecond}
103109
if _, err := Get("https://httpbin.org", ro); err == nil {

example_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,21 @@ func Example_basicGet() {
2525
log.Println(resp.String())
2626
}
2727

28+
func Example_basicGetCustomHTTPClient() {
29+
// This is a very basic GET request
30+
resp, err := grequests.Get("http://httpbin.org/get", &grequests.RequestOptions{HTTPClient: http.DefaultClient})
31+
32+
if err != nil {
33+
log.Println(err)
34+
}
35+
36+
if resp.Ok != true {
37+
log.Println("Request did not return OK")
38+
}
39+
40+
log.Println(resp.String())
41+
}
42+
2843
func Example_proxy() {
2944
proxyURL, err := url.Parse("http://127.0.0.1:8080") // Proxy URL
3045
if err != nil {

request.go

+9
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ type RequestOptions struct {
9191
// KeepAlive specifies the keep-alive period for an active
9292
// network connection. If zero, keep-alive are not enabled.
9393
DialKeepAlive time.Duration
94+
95+
// HTTPClient can be provided if you wish to supply a custom HTTP client
96+
// this is useful if you want to use an OAUTH client with your request
97+
HTTPClient *http.Client
9498
}
9599

96100
func doRegularRequest(requestVerb, url string, ro *RequestOptions) (*Response, error) {
@@ -322,6 +326,11 @@ func (ro RequestOptions) DontUseDefaultClient() bool {
322326
// BuildHTTPClient is a function that will return a custom HTTP client based on the request options provided
323327
// the check is in UseDefaultClient
324328
func BuildHTTPClient(ro RequestOptions) *http.Client {
329+
330+
if ro.HTTPClient != nil {
331+
return ro.HTTPClient
332+
}
333+
325334
// Does the user want to change the defaults?
326335
if !ro.DontUseDefaultClient() {
327336
return http.DefaultClient

0 commit comments

Comments
 (0)