Unverified Commit ed2c2b76 authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #17 from jmank88/webfile-err

check http status code during WebFile reads and return error for non-2XX
parents c68472a9 bb5d585a
......@@ -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
}
......
......@@ -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")
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment