Better handling for not found cases, and test
This commit is contained in:
parent
87acf0aefb
commit
dd79dbed1d
@ -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))
|
||||
|
||||
|
56
web/server_test.go
Normal file
56
web/server_test.go
Normal file
@ -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")
|
||||
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user