From d83508c7691ea98f1f725a96286fcfb2af8a9b07 Mon Sep 17 00:00:00 2001 From: William Petit Date: Thu, 6 Dec 2018 21:53:34 +0100 Subject: [PATCH] Return http.HandlerFunc instead of http.Handler --- static/static.go | 14 ++++++++++---- static/static_test.go | 33 +++++++++++++++++++++++++++++++++ static/testdata/test.txt | 1 + 3 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 static/static_test.go create mode 100644 static/testdata/test.txt diff --git a/static/static.go b/static/static.go index 8ba8a17..0f19d8c 100644 --- a/static/static.go +++ b/static/static.go @@ -6,17 +6,23 @@ import ( ) // Dir serves the files in the given directory or -// uses the given handler to handles missing files -func Dir(dirPath string, stripPrefix string, notFoundHandler http.Handler) http.Handler { +// uses the given HandlerFunc to handles missing files +func Dir(dirPath string, stripPrefix string, notFound http.HandlerFunc) http.HandlerFunc { + root := http.Dir(dirPath) fs := http.FileServer(root) + fn := func(w http.ResponseWriter, r *http.Request) { if _, err := os.Stat(dirPath + r.RequestURI); os.IsNotExist(err) { - notFoundHandler.ServeHTTP(w, r) + notFound.ServeHTTP(w, r) } else { fs.ServeHTTP(w, r) } } + handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn)) - return handler + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler.ServeHTTP(w, r) + }) } diff --git a/static/static_test.go b/static/static_test.go new file mode 100644 index 0000000..ee32a78 --- /dev/null +++ b/static/static_test.go @@ -0,0 +1,33 @@ +package static + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestStaticDir(t *testing.T) { + + req, err := http.NewRequest("GET", "/test.txt", nil) + if err != nil { + t.Fatal(err) + } + + notFound := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("notFound should not be invoked") + }) + + rr := httptest.NewRecorder() + handler := Dir("./testdata", "/", notFound) + + handler.ServeHTTP(rr, req) + + if g, e := rr.Code, http.StatusOK; g != e { + t.Errorf("rr.Code: got '%v', expected '%v'", g, e) + } + + if g, e := rr.Body.String(), "Hello World"; g != e { + t.Errorf("rr.Body.String(): got '%v', expected '%v'", g, e) + } + +} diff --git a/static/testdata/test.txt b/static/testdata/test.txt new file mode 100644 index 0000000..5e1c309 --- /dev/null +++ b/static/testdata/test.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file