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
|
||||
// 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)
|
||||
})
|
||||
}
|
||||
|
33
static/static_test.go
Normal file
33
static/static_test.go
Normal file
@ -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)
|
||||
}
|
||||
|
||||
}
|
1
static/testdata/test.txt
vendored
Normal file
1
static/testdata/test.txt
vendored
Normal file
@ -0,0 +1 @@
|
||||
Hello World
|
Loading…
Reference in New Issue
Block a user