Skip to content

Commit

Permalink
Add context to the requests
Browse files Browse the repository at this point in the history
  • Loading branch information
jespino committed Oct 18, 2021
1 parent a9548c3 commit 4093445
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
12 changes: 9 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goreq

import (
"context"
"crypto/tls"
"errors"
"log"
Expand Down Expand Up @@ -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}
}
Expand Down
10 changes: 8 additions & 2 deletions goreq.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"bytes"
"compress/gzip"
"compress/zlib"
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit 4093445

Please sign in to comment.