Return http.HandlerFunc instead of http.Handler
This commit is contained in:
parent
d62b42ab97
commit
d83508c769
|
@ -6,17 +6,23 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Dir serves the files in the given directory or
|
// Dir serves the files in the given directory or
|
||||||
// uses the given handler to handles missing files
|
// uses the given HandlerFunc to handles missing files
|
||||||
func Dir(dirPath string, stripPrefix string, notFoundHandler http.Handler) http.Handler {
|
func Dir(dirPath string, stripPrefix string, notFound http.HandlerFunc) http.HandlerFunc {
|
||||||
|
|
||||||
root := http.Dir(dirPath)
|
root := http.Dir(dirPath)
|
||||||
fs := http.FileServer(root)
|
fs := http.FileServer(root)
|
||||||
|
|
||||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||||
if _, err := os.Stat(dirPath + r.RequestURI); os.IsNotExist(err) {
|
if _, err := os.Stat(dirPath + r.RequestURI); os.IsNotExist(err) {
|
||||||
notFoundHandler.ServeHTTP(w, r)
|
notFound.ServeHTTP(w, r)
|
||||||
} else {
|
} else {
|
||||||
fs.ServeHTTP(w, r)
|
fs.ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn))
|
handler := http.StripPrefix(stripPrefix, http.HandlerFunc(fn))
|
||||||
return handler
|
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
handler.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
Hello World
|
Loading…
Reference in New Issue