diff --git a/client.go b/client.go index 6c9d9ef..55a6848 100644 --- a/client.go +++ b/client.go @@ -1,6 +1,7 @@ package goreq import ( + "context" "crypto/tls" "errors" "log" @@ -137,15 +138,20 @@ func (client Client) setConnectTimeout(timeout time.Duration) { } } -//Do sends an HTTP request and returns an HTTP response, -//following policy (such as redirects, cookies, auth) as configured on the client. +//Do wraps DoWithContext using context.Background. func (client Client) Do(request Request) (*Response, error) { + return client.DoWithContext(context.Background(), request) +} + +//DoWithContext sends an HTTP request and returns an HTTP response, +//following policy (such as redirects, cookies, auth) as configured on the client. +func (client Client) DoWithContext(ctx context.Context, request Request) (*Response, error) { if erro := client.check(); erro != nil { return nil, erro } - req, err := request.NewRequest() + req, err := request.NewRequestWithContext(ctx) if err != nil { return nil, &Error{Err: err} } diff --git a/goreq.go b/goreq.go index 1a0caa4..dd1c9d2 100644 --- a/goreq.go +++ b/goreq.go @@ -5,6 +5,7 @@ import ( "bytes" "compress/gzip" "compress/zlib" + "context" "encoding/json" "errors" "fmt" @@ -242,8 +243,13 @@ func (r Request) addHeaders(headersMap http.Header) { } } -//NewRequest returns a new Request given a method, URL, and optional body. +// NewRequest wraps NewRequestWithContext using context.Background. func (r Request) NewRequest() (*http.Request, error) { + return r.NewRequestWithContext(context.Background()) +} + +//NewRequestWithContext returns a new Request given a method, URL, and optional body. +func (r Request) NewRequestWithContext(ctx context.Context) (*http.Request, error) { r.valueOrDefault() b, e := prepareRequestBody(r.Body) @@ -278,7 +284,7 @@ func (r Request) NewRequest() (*http.Request, error) { bodyReader = b } - req, err := http.NewRequest(r.Method, r.Uri, bodyReader) + req, err := http.NewRequestWithContext(ctx, r.Method, r.Uri, bodyReader) if err != nil { return nil, err }