Skip to content

Commit

Permalink
util/jsonapi: Add retry using a fresh connection
Browse files Browse the repository at this point in the history
This commit adds a retry for a failing request using a fresh connection.

Signed-off-by: Or Ozeri <[email protected]>
  • Loading branch information
orozery committed Dec 18, 2023
1 parent 6c75ed7 commit 23074ab
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion pkg/util/jsonapi/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ package jsonapi
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"time"

Expand Down Expand Up @@ -81,6 +83,17 @@ func (c *Client) do(method, path string, body []byte) (*Response, error) {
}

resp, err := c.client.Do(req)
if err != nil {
// check for timeout error which could be due to a failed re-used connection
var uerr *url.Error
if errors.As(err, &uerr) && uerr.Timeout() {
// close old connections
c.client.Transport.(*http.Transport).CloseIdleConnections()

// retry request with a fresh connection
resp, err = c.client.Do(req)
}
}
if err != nil {
return nil, fmt.Errorf("unable to perform http request: %w", err)
}
Expand Down Expand Up @@ -108,7 +121,7 @@ func (c *Client) do(method, path string, body []byte) (*Response, error) {
// NewClient returns a new HTTP client.
func NewClient(host string, port uint16, tlsConfig *tls.Config) *Client {
serverURL := "https://" + net.JoinHostPort(host, strconv.Itoa(int(port)))
return &Client{
c := &Client{

Check failure on line 124 in pkg/util/jsonapi/client.go

View workflow job for this annotation

GitHub Actions / unit-tests (1.20)

c declared and not used

Check failure on line 124 in pkg/util/jsonapi/client.go

View workflow job for this annotation

GitHub Actions / e2e-connectivity-test (1.20)

c declared and not used

Check failure on line 124 in pkg/util/jsonapi/client.go

View workflow job for this annotation

GitHub Actions / static-checks

c declared and not used
client: &http.Client{
Transport: &http.Transport{TLSClientConfig: tlsConfig},
Timeout: 3 * time.Second,
Expand Down

0 comments on commit 23074ab

Please sign in to comment.