From ae738d7d87bbd5db7203db7441fb11e32b02df40 Mon Sep 17 00:00:00 2001 From: Hidde Beydals Date: Wed, 13 May 2020 23:51:32 +0200 Subject: [PATCH] feat(getter): add timeout option (#7950) To allow finer grain control over the request when utilizing `getter` as a package. Signed-off-by: Hidde Beydals --- pkg/getter/getter.go | 9 +++++++++ pkg/getter/httpgetter.go | 1 + pkg/getter/httpgetter_test.go | 7 +++++++ 3 files changed, 17 insertions(+) diff --git a/pkg/getter/getter.go b/pkg/getter/getter.go index 4ccc74834..8ee08cb7f 100644 --- a/pkg/getter/getter.go +++ b/pkg/getter/getter.go @@ -18,6 +18,7 @@ package getter import ( "bytes" + "time" "github.com/pkg/errors" @@ -36,6 +37,7 @@ type options struct { username string password string userAgent string + timeout time.Duration } // Option allows specifying various settings configurable by the user for overriding the defaults @@ -81,6 +83,13 @@ func WithTLSClientConfig(certFile, keyFile, caFile string) Option { } } +// WithTimeout sets the timeout for requests +func WithTimeout(timeout time.Duration) Option { + return func(opts *options) { + opts.timeout = timeout + } +} + // Getter is an interface to support GET to the specified URL. type Getter interface { // Get file content by url string diff --git a/pkg/getter/httpgetter.go b/pkg/getter/httpgetter.go index 46c817a9c..858af91ac 100644 --- a/pkg/getter/httpgetter.go +++ b/pkg/getter/httpgetter.go @@ -119,6 +119,7 @@ func (g *HTTPGetter) httpClient() (*http.Client, error) { client := &http.Client{ Transport: transport, + Timeout: g.opts.timeout, } return client, nil diff --git a/pkg/getter/httpgetter_test.go b/pkg/getter/httpgetter_test.go index 0e157eccd..7973b5f85 100644 --- a/pkg/getter/httpgetter_test.go +++ b/pkg/getter/httpgetter_test.go @@ -26,6 +26,7 @@ import ( "strconv" "strings" "testing" + "time" "github.com/pkg/errors" @@ -48,6 +49,7 @@ func TestHTTPGetter(t *testing.T) { join := filepath.Join ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem") insecure := false + timeout := time.Second * 5 // Test with options g, err = NewHTTPGetter( @@ -55,6 +57,7 @@ func TestHTTPGetter(t *testing.T) { WithUserAgent("Groot"), WithTLSClientConfig(pub, priv, ca), WithInsecureSkipVerifyTLS(insecure), + WithTimeout(timeout), ) if err != nil { t.Fatal(err) @@ -93,6 +96,10 @@ func TestHTTPGetter(t *testing.T) { t.Errorf("Expected NewHTTPGetter to contain %t as InsecureSkipVerifyTLs flag, got %t", false, hg.opts.insecureSkipVerifyTLS) } + if hg.opts.timeout != timeout { + t.Errorf("Expected NewHTTPGetter to contain %s as Timeout flag, got %s", timeout, hg.opts.timeout) + } + // Test if setting insecureSkipVerifyTLS is being passed to the ops insecure = true