Skip to content

Commit

Permalink
aws: util always read resp.body (#6734)
Browse files Browse the repository at this point in the history
Signed-off-by: Johannes Larsson <johannes.a.larsson@gmail.com>
  • Loading branch information
johanneslarsson committed May 6, 2024
1 parent e011f60 commit 7c0278e
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions internal/providers/aws/util.go
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/open-policy-agent/opa/logging"
)

// DoRequestWithClient is a convenience function to get the body of an http response with
// DoRequestWithClient is a convenience function to get the body of a http response with
// appropriate error-handling boilerplate and logging.
func DoRequestWithClient(req *http.Request, client *http.Client, desc string, logger logging.Logger) ([]byte, error) {
resp, err := client.Do(req)
Expand All @@ -24,22 +24,18 @@ func DoRequestWithClient(req *http.Request, client *http.Client, desc string, lo
"headers": resp.Header,
}).Debug("Received response from " + desc + " service.")

if resp.StatusCode != 200 {
if logger.GetLevel() == logging.Debug {
body, err := io.ReadAll(resp.Body)
if err == nil {
logger.Debug("Error response with response body: %s", body)
}
}
// could be 404 for role that's not available, but cover all the bases
return nil, errors.New(desc + " HTTP request returned unexpected status: " + resp.Status)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
// deal with problems reading the body, whatever those might be
return nil, errors.New(desc + " HTTP response body could not be read: " + err.Error())
}

if resp.StatusCode != 200 {
if logger.GetLevel() == logging.Debug {
logger.Debug("Error response with response body: %s", body)
}
// could be 404 for role that's not available, but cover all the bases
return nil, errors.New(desc + " HTTP request returned unexpected status: " + resp.Status)
}
return body, nil
}

0 comments on commit 7c0278e

Please sign in to comment.