Skip to content

Commit f259b79

Browse files
author
Pedro De Brito
committed
Add DoWithCustomClient function
1 parent c54f99b commit f259b79

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

request.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,37 @@ func DoWithStringResponse(params Params) (result string, returnErr error) {
114114
return string(bodyBytes), nil
115115
}
116116

117+
// DoWithCustomClient is the same as Do but will make the request using the
118+
// supplied http.Client instead of the cachedClient.
119+
func DoWithCustomClient(params Params, responseBody interface{}, client *http.Client) (returnErr error) {
120+
req, err := createRequest(params)
121+
if err != nil {
122+
return fmt.Errorf("failed to create request: %w", err)
123+
}
124+
125+
res, err := client.Do(req)
126+
if err != nil {
127+
return fmt.Errorf("failed to send request: %w", err)
128+
}
129+
130+
defer func() {
131+
if cErr := res.Body.Close(); cErr != nil && returnErr == nil {
132+
returnErr = cErr
133+
}
134+
}()
135+
136+
err = checkResponseCode(res, params.ExpectedResponseCode)
137+
if err != nil {
138+
return err
139+
}
140+
141+
if responseBody == nil {
142+
return nil
143+
}
144+
145+
return json.NewDecoder(res.Body).Decode(responseBody)
146+
}
147+
117148
func createRequest(params Params) (*http.Request, error) {
118149
reader, err := convertToReader(params.Body)
119150
if err != nil {

request_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@ import (
44
"fmt"
55
"io/ioutil"
66
"net/http"
7+
"net/http/cookiejar"
78
"net/http/httptest"
9+
"net/url"
810
"strings"
911
"testing"
1012
"time"
1113

1214
"github.com/fastbill/go-httperrors/v2"
1315
"github.com/stretchr/testify/assert"
16+
"github.com/stretchr/testify/require"
1417
)
1518

1619
type Input struct {
@@ -318,6 +321,29 @@ func TestDoWithStringResponse(t *testing.T) {
318321
})
319322
}
320323

324+
func TestDoWithCustomClient(t *testing.T) {
325+
customClient := GetClient()
326+
327+
jar, err := cookiejar.New(nil)
328+
require.NoError(t, err)
329+
customClient.Jar = jar
330+
331+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
332+
w.Header().Set("Set-Cookie", "foo=bar")
333+
w.WriteHeader(http.StatusOK)
334+
}))
335+
336+
u, err := url.Parse(ts.URL)
337+
require.NoError(t, err)
338+
params := Params{
339+
URL: u.String(),
340+
}
341+
err = DoWithCustomClient(params, nil, customClient)
342+
require.NoError(t, err)
343+
344+
require.Equal(t, "foo=bar", jar.Cookies(u)[0].String())
345+
}
346+
321347
func TestGet(t *testing.T) {
322348
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
323349
assert.Equal(t, r.Method, http.MethodGet)

0 commit comments

Comments
 (0)