Commit bb5d585a authored by jmank88's avatar jmank88

check http status code during WebFile reads and return error for non-2XX

parent c68472a9
...@@ -2,6 +2,7 @@ package files ...@@ -2,6 +2,7 @@ package files
import ( import (
"errors" "errors"
"fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
...@@ -31,10 +32,14 @@ func NewWebFile(url *url.URL) *WebFile { ...@@ -31,10 +32,14 @@ func NewWebFile(url *url.URL) *WebFile {
// reads will keep reading from the HTTP Request body. // reads will keep reading from the HTTP Request body.
func (wf *WebFile) Read(b []byte) (int, error) { func (wf *WebFile) Read(b []byte) (int, error) {
if wf.body == nil { if wf.body == nil {
resp, err := http.Get(wf.url.String()) s := wf.url.String()
resp, err := http.Get(s)
if err != nil { if err != nil {
return 0, err 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.body = resp.Body
wf.contentLength = resp.ContentLength wf.contentLength = resp.ContentLength
} }
......
...@@ -10,8 +10,9 @@ import ( ...@@ -10,8 +10,9 @@ import (
) )
func TestWebFile(t *testing.T) { func TestWebFile(t *testing.T) {
const content = "Hello world!"
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!") fmt.Fprintf(w, content)
})) }))
defer s.Close() defer s.Close()
...@@ -24,7 +25,24 @@ func TestWebFile(t *testing.T) { ...@@ -24,7 +25,24 @@ func TestWebFile(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if string(body) != "Hello world!" { if string(body) != content {
t.Fatal("should have read the web file") 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