Skip to content

Commit

Permalink
Return errors when response reading fails
Browse files Browse the repository at this point in the history
Previously we got partial results instead, and we were having this
happening silently. If we were lucky, the json parsing failed though.
  • Loading branch information
ttimonen committed Apr 7, 2023
1 parent 7776f92 commit 1d378b9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
10 changes: 8 additions & 2 deletions okta/requestExecutor.go
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,10 @@ func CheckResponseForError(resp *http.Response) error {
}
}
}
bodyBytes, _ := io.ReadAll(resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
copyBodyBytes := make([]byte, len(bodyBytes))
copy(copyBodyBytes, bodyBytes)
_ = resp.Body.Close()
Expand All @@ -668,7 +671,10 @@ func buildResponse(resp *http.Response, re *RequestExecutor, v interface{}) (*Re
if err != nil {
return response, err
}
bodyBytes, _ := io.ReadAll(resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
copyBodyBytes := make([]byte, len(bodyBytes))
copy(copyBodyBytes, bodyBytes)
_ = resp.Body.Close() // close it to avoid memory leaks
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/request_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ func (r readerFun) Read(p []byte) (n int, err error) { return r(p) }
type slowTransport struct{}

// RoundTrip, part of http.Transport interface. This servers 42 as a JSON response, but slowly.
// In particular, we serve the response immediately, but getting the body takes a second.
// In particular, we serve the response immediately, but getting the body takes some milliseconds.
func (t slowTransport) RoundTrip(req *http.Request) (*http.Response, error) {
realBody := strings.NewReader("42")
// This body takes 1 second to read. It also needs a valid context for the whole duration.
// This body takes 1 millisecond to read. It also needs a valid context for the whole duration.
slowBody := func(p []byte) (n int, err error) {
select {
case <-req.Context().Done():
return 0, req.Context().Err()
case <-time.After(1 * time.Second):
case <-time.After(1 * time.Millisecond):
return realBody.Read(p)
}
}
Expand Down

0 comments on commit 1d378b9

Please sign in to comment.