Skip to content

Commit c37dab3

Browse files
committed
Make underlying httpClient configurable
1 parent 6df3e33 commit c37dab3

File tree

2 files changed

+28
-19
lines changed

2 files changed

+28
-19
lines changed

client.go

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"encoding/base64"
88
"encoding/json"
99
"fmt"
10-
"net"
1110
"net/http"
1211
"net/url"
1312
"reflect"
@@ -31,23 +30,6 @@ var (
3130
contextType = reflect.TypeOf(new(context.Context)).Elem()
3231

3332
log = logging.Logger("rpc")
34-
35-
_defaultHTTPClient = &http.Client{
36-
Transport: &http.Transport{
37-
Proxy: http.ProxyFromEnvironment,
38-
DialContext: (&net.Dialer{
39-
Timeout: 30 * time.Second,
40-
KeepAlive: 30 * time.Second,
41-
DualStack: true,
42-
}).DialContext,
43-
ForceAttemptHTTP2: true,
44-
MaxIdleConns: 100,
45-
MaxIdleConnsPerHost: 100,
46-
IdleConnTimeout: 90 * time.Second,
47-
TLSHandshakeTimeout: 10 * time.Second,
48-
ExpectContinueTimeout: 1 * time.Second,
49-
},
50-
}
5133
)
5234

5335
// ErrClient is an error which occurred on the client side the library
@@ -160,7 +142,7 @@ func httpClient(ctx context.Context, addr string, namespace string, outs []inter
160142

161143
hreq.Header.Set("Content-Type", "application/json")
162144

163-
httpResp, err := _defaultHTTPClient.Do(hreq)
145+
httpResp, err := config.httpClient.Do(hreq)
164146
if err != nil {
165147
return clientResponse{}, &RPCConnectionError{err}
166148
}

options.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package jsonrpc
22

33
import (
4+
"net"
5+
"net/http"
46
"reflect"
57
"time"
68

@@ -17,6 +19,8 @@ type Config struct {
1719
paramEncoders map[reflect.Type]ParamEncoder
1820
errors *Errors
1921

22+
httpClient *http.Client
23+
2024
noReconnect bool
2125
proxyConnFactory func(func() (*websocket.Conn, error)) func() (*websocket.Conn, error) // for testing
2226
}
@@ -31,6 +35,23 @@ func defaultConfig() Config {
3135
timeout: 30 * time.Second,
3236

3337
paramEncoders: map[reflect.Type]ParamEncoder{},
38+
39+
httpClient: &http.Client{
40+
Transport: &http.Transport{
41+
Proxy: http.ProxyFromEnvironment,
42+
DialContext: (&net.Dialer{
43+
Timeout: 30 * time.Second,
44+
KeepAlive: 30 * time.Second,
45+
DualStack: true,
46+
}).DialContext,
47+
ForceAttemptHTTP2: true,
48+
MaxIdleConns: 100,
49+
MaxIdleConnsPerHost: 100,
50+
IdleConnTimeout: 90 * time.Second,
51+
TLSHandshakeTimeout: 10 * time.Second,
52+
ExpectContinueTimeout: 1 * time.Second,
53+
},
54+
},
3455
}
3556
}
3657

@@ -75,3 +96,9 @@ func WithErrors(es Errors) func(c *Config) {
7596
c.errors = &es
7697
}
7798
}
99+
100+
func WithHTTPClient(h *http.Client) func(c *Config) {
101+
return func(c *Config) {
102+
c.httpClient = h
103+
}
104+
}

0 commit comments

Comments
 (0)