Skip to content

Commit 452c429

Browse files
Add support for custom http.Client via ClientOption (#209)
1 parent 6655f6b commit 452c429

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

typesense/client.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ type ClientConfig struct {
155155
CircuitBreakerTimeout time.Duration
156156
CircuitBreakerReadyToTrip circuit.GoBreakerReadyToTripFunc
157157
CircuitBreakerOnStateChange circuit.GoBreakerOnStateChangeFunc
158+
CustomHTTPClient *http.Client
158159
}
159160

160161
type ClientOption func(*Client)
@@ -304,6 +305,12 @@ func WithClientConfig(config *ClientConfig) ClientOption {
304305
}
305306
}
306307

308+
func WithCustomHTTPClient(client *http.Client) ClientOption {
309+
return func(c *Client) {
310+
c.apiConfig.CustomHTTPClient = client
311+
}
312+
}
313+
307314
func NewClient(opts ...ClientOption) *Client {
308315
c := &Client{apiConfig: &ClientConfig{
309316
RetryInterval: defaultRetryInterval,
@@ -328,12 +335,16 @@ func NewClient(opts ...ClientOption) *Client {
328335
circuit.WithGoBreakerReadyToTrip(c.apiConfig.CircuitBreakerReadyToTrip),
329336
circuit.WithGoBreakerOnStateChange(c.apiConfig.CircuitBreakerOnStateChange),
330337
)
338+
client := c.apiConfig.CustomHTTPClient
339+
if client == nil {
340+
client = &http.Client{
341+
Timeout: c.apiConfig.ConnectionTimeout,
342+
}
343+
}
331344
httpClient := circuit.NewHTTPClient(
332345
circuit.WithHTTPRequestDoer(
333346
NewAPICall(
334-
&http.Client{
335-
Timeout: c.apiConfig.ConnectionTimeout,
336-
},
347+
client,
337348
c.apiConfig,
338349
)),
339350
circuit.WithCircuitBreaker(cb),

typesense/client_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package typesense
22

33
import (
4+
"net/http"
45
"reflect"
56
"testing"
67
"time"
@@ -238,6 +239,19 @@ func TestClientConfigOptions(t *testing.T) {
238239
assert.NotNil(t, client.apiClient)
239240
},
240241
},
242+
{
243+
name: "WithCustomHTTPClient",
244+
options: []ClientOption{
245+
WithCustomHTTPClient(&http.Client{
246+
Timeout: 10 * time.Second,
247+
}),
248+
},
249+
verify: func(t *testing.T, client *Client) {
250+
assert.NotNil(t, client.apiConfig.CustomHTTPClient)
251+
assert.Equal(t, 10*time.Second, client.apiConfig.CustomHTTPClient.Timeout)
252+
assert.NotNil(t, client.apiClient)
253+
},
254+
},
241255
}
242256
for _, tt := range tests {
243257
t.Run(tt.name, func(t *testing.T) {

0 commit comments

Comments
 (0)