From cfcd3f931e596073f7f5f0fed5e062b4988fc891 Mon Sep 17 00:00:00 2001 From: Pavel Busko Date: Fri, 10 May 2024 14:08:42 +0200 Subject: [PATCH] Do not initialize http.Client during each request to a remote location Signed-off-by: Pavel Busko --- pkg/blob/downloader.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/pkg/blob/downloader.go b/pkg/blob/downloader.go index 9e00d97c1e..53c46e5a99 100644 --- a/pkg/blob/downloader.go +++ b/pkg/blob/downloader.go @@ -28,6 +28,14 @@ type Logger interface { Writer() io.Writer } +type DownloaderOption func(d *downloader) + +func WithClient(client *http.Client) DownloaderOption { + return func(d *downloader) { + d.client = client + } +} + type Downloader interface { Download(ctx context.Context, pathOrURI string) (Blob, error) } @@ -35,13 +43,21 @@ type Downloader interface { type downloader struct { logger Logger baseCacheDir string + client *http.Client } -func NewDownloader(logger Logger, baseCacheDir string) Downloader { - return &downloader{ +func NewDownloader(logger Logger, baseCacheDir string, opts ...DownloaderOption) Downloader { + d := &downloader{ logger: logger, baseCacheDir: baseCacheDir, + client: http.DefaultClient, } + + for _, opt := range opts { + opt(d) + } + + return d } func (d *downloader) Download(ctx context.Context, pathOrURI string) (Blob, error) { @@ -146,7 +162,7 @@ func (d *downloader) downloadAsStream(ctx context.Context, uri string, etag stri req.Header.Set("If-None-Match", etag) } - resp, err := (&http.Client{}).Do(req) //nolint:bodyclose + resp, err := d.client.Do(req) //nolint:bodyclose if err != nil { return nil, "", err }