Skip to content

Commit

Permalink
feat: show first 32 bytes of response body on download error
Browse files Browse the repository at this point in the history
Fixes #7919

Signed-off-by: Andrey Smirnov <andrey.smirnov@siderolabs.com>
  • Loading branch information
smira committed Nov 8, 2023
1 parent 75d3987 commit 8245361
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
8 changes: 7 additions & 1 deletion pkg/download/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package download

import (
"bytes"
"context"
"encoding/base64"
"fmt"
Expand Down Expand Up @@ -238,7 +239,12 @@ func download(req *http.Request, options *downloadOptions) (data []byte, err err
}

if resp.StatusCode != http.StatusOK {
return data, retry.ExpectedError(fmt.Errorf("failed to download config, received %d", resp.StatusCode))
// try to read first 32 bytes of the response body
// to provide more context in case of error
data, _ = io.ReadAll(io.LimitReader(resp.Body, 32)) //nolint:errcheck // as error already happened, we don't care much about this one
data = bytes.ToValidUTF8(data, nil)

return data, retry.ExpectedError(fmt.Errorf("failed to download config, status code %d, body %q", resp.StatusCode, string(data)))
}

data, err = io.ReadAll(resp.Body)
Expand Down
3 changes: 2 additions & 1 deletion pkg/download/download_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func TestDownload(t *testing.T) {
w.Write([]byte("ZGF0YQ==")) //nolint:errcheck
case "/404":
w.WriteHeader(http.StatusNotFound)
fmt.Fprintln(w, "not found")
default:
w.WriteHeader(http.StatusInternalServerError)
}
Expand Down Expand Up @@ -109,7 +110,7 @@ func TestDownload(t *testing.T) {
name: "failure 404",
path: "/404",
opts: []download.Option{download.WithTimeout(2 * time.Second)},
expectedError: "failed to download config, received 404",
expectedError: "failed to download config, status code 404, body \"not found\\n\"",
},
{
name: "retry endpoint change",
Expand Down

0 comments on commit 8245361

Please sign in to comment.