From 4fed0b87e40002a25868766c1d14ce74d1eaed69 Mon Sep 17 00:00:00 2001 From: jmank88 Date: Mon, 22 Apr 2019 16:25:20 -0500 Subject: [PATCH] check http status code during WebFile reads and return error for non-2XX This commit was moved from ipfs/go-ipfs-files@bb5d585a9e937dc20d6f15fd415c2d5e26f0ed3b --- files/webfile.go | 7 ++++++- files/webfile_test.go | 24 +++++++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/files/webfile.go b/files/webfile.go index 0e26e277f..58208e391 100644 --- a/files/webfile.go +++ b/files/webfile.go @@ -2,6 +2,7 @@ package files import ( "errors" + "fmt" "io" "net/http" "net/url" @@ -31,10 +32,14 @@ func NewWebFile(url *url.URL) *WebFile { // reads will keep reading from the HTTP Request body. func (wf *WebFile) Read(b []byte) (int, error) { if wf.body == nil { - resp, err := http.Get(wf.url.String()) + s := wf.url.String() + resp, err := http.Get(s) if err != nil { return 0, err } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return 0, fmt.Errorf("got non-2XX status code %d: %s", resp.StatusCode, s) + } wf.body = resp.Body wf.contentLength = resp.ContentLength } diff --git a/files/webfile_test.go b/files/webfile_test.go index ea8f0d7ae..11eaa2de2 100644 --- a/files/webfile_test.go +++ b/files/webfile_test.go @@ -10,8 +10,9 @@ import ( ) func TestWebFile(t *testing.T) { + const content = "Hello world!" s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello world!") + fmt.Fprintf(w, content) })) defer s.Close() @@ -24,7 +25,24 @@ func TestWebFile(t *testing.T) { if err != nil { t.Fatal(err) } - if string(body) != "Hello world!" { - t.Fatal("should have read the web file") + if string(body) != content { + t.Fatalf("expected %q but got %q", content, string(body)) + } +} + +func TestWebFile_notFound(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "File not found.", http.StatusNotFound) + })) + defer s.Close() + + u, err := url.Parse(s.URL) + if err != nil { + t.Fatal(err) + } + wf := NewWebFile(u) + _, err = ioutil.ReadAll(wf) + if err == nil { + t.Fatal("expected error") } }