From 951cf2c15b346dfa1f9bf1ecf3635e6c8ddf089a Mon Sep 17 00:00:00 2001 From: Jim McDonald Date: Fri, 25 Oct 2024 22:02:18 +0100 Subject: [PATCH] Allow custom HTTP client. --- http/parameters.go | 10 ++++++++++ http/service.go | 27 +++++++++++++++------------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/http/parameters.go b/http/parameters.go index 2f91e076..ab679a5b 100644 --- a/http/parameters.go +++ b/http/parameters.go @@ -15,6 +15,7 @@ package http import ( "errors" + "net/http" "time" "github.com/attestantio/go-eth2-client/metrics" @@ -34,6 +35,7 @@ type parameters struct { hooks *Hooks reducedMemoryUsage bool customSpecSupport bool + client *http.Client } // Parameter is the interface for service parameters. @@ -134,6 +136,14 @@ func WithCustomSpecSupport(customSpecSupport bool) Parameter { }) } +// WithHTTPClient provides a custom HTTP client for communication with the HTTP server. +// If not supplied then a standard HTTP client is used. +func WithHTTPClient(client *http.Client) Parameter { + return parameterFunc(func(p *parameters) { + p.client = client + }) +} + // parseAndCheckParameters parses and checks parameters to ensure that mandatory parameters are present and correct. func parseAndCheckParameters(params ...Parameter) (*parameters, error) { parameters := parameters{ diff --git a/http/service.go b/http/service.go index 8077064c..ddf98843 100644 --- a/http/service.go +++ b/http/service.go @@ -95,18 +95,21 @@ func New(ctx context.Context, params ...Parameter) (client.Service, error) { } } - httpClient := &http.Client{ - Transport: &http.Transport{ - DialContext: (&net.Dialer{ - Timeout: parameters.timeout, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 64, - MaxConnsPerHost: 64, - MaxIdleConnsPerHost: 64, - IdleConnTimeout: 600 * time.Second, - }, + httpClient := parameters.client + if httpClient == nil { + httpClient = &http.Client{ + Transport: &http.Transport{ + DialContext: (&net.Dialer{ + Timeout: parameters.timeout, + KeepAlive: 30 * time.Second, + DualStack: true, + }).DialContext, + MaxIdleConns: 64, + MaxConnsPerHost: 64, + MaxIdleConnsPerHost: 64, + IdleConnTimeout: 600 * time.Second, + }, + } } base, address, err := parseAddress(parameters.address)