Skip to content

Commit

Permalink
Merge pull request ipfs/go-ipfs-files#17 from jmank88/webfile-err
Browse files Browse the repository at this point in the history
check http status code during WebFile reads and return error for non-2XX

This commit was moved from ipfs/go-ipfs-files@ed2c2b7
  • Loading branch information
Stebalien committed Apr 22, 2019
2 parents 9ea7640 + 4fed0b8 commit cf1d3b4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
7 changes: 6 additions & 1 deletion files/webfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package files

import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -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
}
Expand Down
24 changes: 21 additions & 3 deletions files/webfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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")
}
}

0 comments on commit cf1d3b4

Please sign in to comment.