Skip to content

Commit

Permalink
Do not initialize http.Client during each request to a remote location
Browse files Browse the repository at this point in the history
  • Loading branch information
pbusko committed May 10, 2024
1 parent 0a39de0 commit aee1641
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions pkg/blob/downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,36 @@ 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)
}

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) {
Expand Down Expand Up @@ -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)

Check failure on line 165 in pkg/blob/downloader.go

View workflow job for this annotation

GitHub Actions / test (macos)

response body must be closed (bodyclose)

Check failure on line 165 in pkg/blob/downloader.go

View workflow job for this annotation

GitHub Actions / test (linux)

response body must be closed (bodyclose)

Check failure on line 165 in pkg/blob/downloader.go

View workflow job for this annotation

GitHub Actions / test (windows-lcow)

response body must be closed (bodyclose)

Check failure on line 165 in pkg/blob/downloader.go

View workflow job for this annotation

GitHub Actions / test (windows-wcow)

response body must be closed (bodyclose)
if err != nil {
return nil, "", err
}
Expand Down

0 comments on commit aee1641

Please sign in to comment.