From acabdfcebc7cdbe71d95a57b8fb97b2d08546fbc Mon Sep 17 00:00:00 2001 From: Eamonn O'Toole Date: Wed, 23 Oct 2024 13:53:59 +0100 Subject: [PATCH] Create new http request on each retry (#125) --- pkg/token/httpclient/httpclient_test.go | 2 +- pkg/token/issuertoken/issuertoken.go | 26 ++++++++++++++++++------- pkg/token/token-util/token-util.go | 1 + 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/pkg/token/httpclient/httpclient_test.go b/pkg/token/httpclient/httpclient_test.go index 56cca01..9cc4626 100644 --- a/pkg/token/httpclient/httpclient_test.go +++ b/pkg/token/httpclient/httpclient_test.go @@ -126,7 +126,7 @@ func setTestCase() ([]testCaseIssuer, []testCaseIdentity) { name: "no context", url: "https://hpe-greenlake-tenant.okta.com/oauth2/default", ctx: nil, - err: errors.New("net/http: nil Context"), + err: errors.New("network error in post to get token"), }, { name: "status code 400", diff --git a/pkg/token/issuertoken/issuertoken.go b/pkg/token/issuertoken/issuertoken.go index 5cb8f37..7271860 100644 --- a/pkg/token/issuertoken/issuertoken.go +++ b/pkg/token/issuertoken/issuertoken.go @@ -40,15 +40,16 @@ func GenerateToken( return "", err } - // Create the request - req, err := http.NewRequestWithContext(ctx, http.MethodPost, clientURL, strings.NewReader(params.Encode())) - if err != nil { - return "", err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - // Execute the request, with retries resp, err := tokenutil.DoRetries(func() (*http.Response, error) { + // Create the request + req, errReq := createRequest(ctx, params, clientURL) + if errReq != nil { + return nil, errReq + } + // Close the request after use, i.e. don't reuse the TCP connection + req.Close = true + return httpClient.Do(req) }, retryLimit) if err != nil { @@ -76,6 +77,17 @@ func GenerateToken( return token.AccessToken, nil } +// createRequest creates a new http request +func createRequest(ctx context.Context, params url.Values, clientURL string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, clientURL, strings.NewReader(params.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + return req, nil +} + // generateParamsAndURL generates the parameters and URL for the request func generateParamsAndURL(clientID, clientSecret, identityServiceURL, iamVersion string) (url.Values, string, error) { params := url.Values{} diff --git a/pkg/token/token-util/token-util.go b/pkg/token/token-util/token-util.go index 2e7e90b..05d1fb6 100644 --- a/pkg/token/token-util/token-util.go +++ b/pkg/token/token-util/token-util.go @@ -89,6 +89,7 @@ func DoRetries(call func() (*http.Response, error), retries int) (*http.Response break } + log.Printf("Retrying request, retries left: %v", retries) time.Sleep(3 * time.Second) retries-- }