diff --git a/api_client_iter.go b/api_client_iter.go index ccef323..a965105 100644 --- a/api_client_iter.go +++ b/api_client_iter.go @@ -25,7 +25,6 @@ func getIterResult( if err != nil { return nil, fmt.Errorf("failed to fetch next page: %w", err) } - defer response.Body.Close() body, err := io.ReadAll(response.Body) @@ -33,6 +32,14 @@ func getIterResult( return nil, fmt.Errorf("failed to read response: %w", err) } + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf( + "got http status code %d status while fetching next page: %s", + response.StatusCode, + body, + ) + } + type ResponseWithNext struct { Next string `json:"next"` } diff --git a/api_client_iter_test.go b/api_client_iter_test.go index 89a366c..70f50f1 100644 --- a/api_client_iter_test.go +++ b/api_client_iter_test.go @@ -55,7 +55,7 @@ func TestIterGet(t *testing.T) { } -func TestIterGetBadResponse(t *testing.T) { +func TestIterGetBadResponseJson(t *testing.T) { ct := newClientTest( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "/leaksdb/sources", r.URL.Path) @@ -82,6 +82,39 @@ func TestIterGetBadResponse(t *testing.T) { assert.Equal(t, 1, lastPageIndex, "Didn't get the expected number of pages") } +func TestIterGetBadResponseStatus(t *testing.T) { + ct := newClientTest( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Correct response structure but bad response status code. + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(`"some error"`)) + }), + ) + defer ct.Close() + + lastPageIndex := 0 + + for result, err := range ct.apiClient.IterGet( + "/leaksdb/sources", + nil, + ) { + lastPageIndex = lastPageIndex + 1 + if lastPageIndex > 2 { + // We are going crazy here... + break + } + assert.ErrorContains( + t, + err, + `got http status code 400 status while fetching next page: "some error"`, + "Bad HTTP status should trigger an error", + ) + assert.Nil(t, result, "result should be nil on errors") + } + + assert.Equal(t, 1, lastPageIndex, "Didn't get the expected number of pages") +} + func TestIterPostJson(t *testing.T) { ct := newClientTest( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {