From e270bd45fe66a9941d9a85ae859f774a76b2a7e8 Mon Sep 17 00:00:00 2001 From: Nathan Smith <12156185+nsmith5@users.noreply.github.com> Date: Sat, 11 Dec 2021 15:57:11 -0800 Subject: [PATCH] Make client request timeout configurable with `WithTimeout` client option (#272) * Add timeout options for client Signed-off-by: Nathan Smith * Git ignore Vim swap files Signed-off-by: Nathan Smith --- .gitignore | 2 ++ pkg/api/client.go | 10 ++++++++++ pkg/api/options_test.go | 7 ++++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 96e73ec38..5a6ab76cd 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ hack/tools/bin /server /fulcio +# Vim +*.swp diff --git a/pkg/api/client.go b/pkg/api/client.go index a8d367fcd..896beef1f 100644 --- a/pkg/api/client.go +++ b/pkg/api/client.go @@ -25,6 +25,7 @@ import ( "net/http" "net/url" "path" + "time" ) type CertificateResponse struct { @@ -54,6 +55,7 @@ func NewClient(url *url.URL, opts ...ClientOption) Client { baseURL: url, client: &http.Client{ Transport: createRoundTripper(http.DefaultTransport, o), + Timeout: o.Timeout, }, } } @@ -120,6 +122,7 @@ func (c *client) SigningCert(cr CertificateRequest, token string) (*CertificateR type clientOptions struct { UserAgent string + Timeout time.Duration } func makeOptions(opts ...ClientOption) *clientOptions { @@ -134,6 +137,13 @@ func makeOptions(opts ...ClientOption) *clientOptions { return o } +// WithTimeout sets the request timeout for the client +func WithTimeout(timeout time.Duration) ClientOption { + return func(o *clientOptions) { + o.Timeout = timeout + } +} + // WithUserAgent sets the media type of the signature. func WithUserAgent(userAgent string) ClientOption { return func(o *clientOptions) { diff --git a/pkg/api/options_test.go b/pkg/api/options_test.go index 5f244a63c..a186665f8 100644 --- a/pkg/api/options_test.go +++ b/pkg/api/options_test.go @@ -18,6 +18,7 @@ import ( "net/http" "net/url" "testing" + "time" "github.com/google/go-cmp/cmp" ) @@ -35,6 +36,10 @@ func TestMakeOptions(t *testing.T) { desc: "WithUserAgent", opts: []ClientOption{WithUserAgent("test user agent")}, want: &clientOptions{UserAgent: "test user agent"}, + }, { + desc: "WithTimeout", + opts: []ClientOption{WithTimeout(7 * time.Second)}, + want: &clientOptions{Timeout: 7 * time.Second}, }} for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { @@ -110,7 +115,7 @@ func TestSanity(t *testing.T) { t.Fatalf("url.Parse(SigstorePublicServerURL) returned error: %v", err) } - got := NewClient(testURL, WithUserAgent("sanity test")) + got := NewClient(testURL, WithUserAgent("sanity test"), WithTimeout(11*time.Second)) if got == nil { t.Fatalf(`New(testURL, WithUserAgent("sanity test")) returned nil`) }