Skip to content

Commit

Permalink
Make client request timeout configurable with WithTimeout client op…
Browse files Browse the repository at this point in the history
…tion (#272)

* Add timeout options for client

Signed-off-by: Nathan Smith <nathan@nfsmith.ca>

* Git ignore Vim swap files

Signed-off-by: Nathan Smith <nathan@nfsmith.ca>
  • Loading branch information
nsmith5 committed Dec 11, 2021
1 parent 94047c6 commit e270bd4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,5 @@ hack/tools/bin
/server
/fulcio

# Vim
*.swp
10 changes: 10 additions & 0 deletions pkg/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"net/http"
"net/url"
"path"
"time"
)

type CertificateResponse struct {
Expand Down Expand Up @@ -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,
},
}
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down
7 changes: 6 additions & 1 deletion pkg/api/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"net/http"
"net/url"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)
Expand All @@ -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) {
Expand Down Expand Up @@ -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`)
}
Expand Down

0 comments on commit e270bd4

Please sign in to comment.