From dd79dbed1d75038741f13769e6b1632bc4576fe5 Mon Sep 17 00:00:00 2001 From: Justin Hawkins Date: Mon, 4 Oct 2021 13:27:46 +1030 Subject: [PATCH] Better handling for not found cases, and test --- web/server.go | 12 ++++++++-- web/server_test.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 web/server_test.go diff --git a/web/server.go b/web/server.go index 92a1fd4..97040d3 100644 --- a/web/server.go +++ b/web/server.go @@ -56,7 +56,11 @@ func getStatic(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFS(webFS, "data/wrapper.tmpl", "data/"+path) if err != nil { - panic(err) + log.Printf("when fetching: %s got: %s", path, err) + w.Header().Add("Content-Type", "text/plain") + w.WriteHeader(http.StatusNotFound) + w.Write([]byte("not found")) + return } log.Printf("req: %s", r.URL.Path) @@ -78,7 +82,11 @@ func getStatic(w http.ResponseWriter, r *http.Request) { otherStatic, err := webFS.ReadFile("data/" + path) if err != nil { - log.Fatalf("problem with '%s': %v", path, err) + log.Printf("when fetching: %s got: %s", path, err) + w.Header().Add("Content-Type", "text/plain") + w.WriteHeader(http.StatusNotFound) + w.Write([]byte("not found")) + return } w.Header().Set("Content-Type", mime.TypeByExtension(extension)) diff --git a/web/server_test.go b/web/server_test.go new file mode 100644 index 0000000..5c61b31 --- /dev/null +++ b/web/server_test.go @@ -0,0 +1,56 @@ +package web + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHome(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/", nil) + w := httptest.NewRecorder() + getStatic(w, req) + res := w.Result() + defer res.Body.Close() + data, err := ioutil.ReadAll(res.Body) + if err != nil { + t.Errorf("expected error to be nil got %v", err) + } + if !strings.Contains(string(data), "DAU") { + t.Errorf("does not look like correct homepage at /") + } + if res.Header.Get("Content-Type") != "text/html; charset=utf-8" { + t.Errorf("wrong content type for / - %s", res.Header.Get("Content-Type")) + } + +} + +func TestNotFound(t *testing.T) { + + notFounds := []string{ + "/abc.html", "/foo.html", "/foo.html", "/../foo.html", + "/foo.gif", + } + + for _, nf := range notFounds { + + req := httptest.NewRequest(http.MethodGet, nf, nil) + w := httptest.NewRecorder() + getStatic(w, req) + res := w.Result() + defer res.Body.Close() + b, err := ioutil.ReadAll(res.Body) + if err != nil { + t.Errorf("expected error to be nil got %v", err) + } + if string(b) != "not found" { + t.Errorf("expected body to be not found, not '%s'", string(b)) + } + if res.Header.Get("Content-Type") != "text/plain" { + t.Error("Wrong content type for not found") + + } + } +}