Skip to content

Commit

Permalink
Allow custom HTTP client.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcdee committed Oct 25, 2024
1 parent c1ba6e0 commit 951cf2c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
10 changes: 10 additions & 0 deletions http/parameters.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package http

import (
"errors"
"net/http"
"time"

"github.com/attestantio/go-eth2-client/metrics"
Expand All @@ -34,6 +35,7 @@ type parameters struct {
hooks *Hooks
reducedMemoryUsage bool
customSpecSupport bool
client *http.Client
}

// Parameter is the interface for service parameters.
Expand Down Expand Up @@ -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{
Expand Down
27 changes: 15 additions & 12 deletions http/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 951cf2c

Please sign in to comment.