Skip to content

Commit

Permalink
Create new http request on each retry (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
eamonnotoole authored Oct 23, 2024
1 parent 21454eb commit acabdfc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
2 changes: 1 addition & 1 deletion pkg/token/httpclient/httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
26 changes: 19 additions & 7 deletions pkg/token/issuertoken/issuertoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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{}
Expand Down
1 change: 1 addition & 0 deletions pkg/token/token-util/token-util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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--
}
Expand Down

0 comments on commit acabdfc

Please sign in to comment.