Browse Source

Return http.HandlerFunc instead of http.Handler

extension
wpetit 3 years ago
parent
commit
d83508c769
3 changed files with 44 additions and 4 deletions
  1. +10
    -4
      static/static.go
  2. +33
    -0
      static/static_test.go
  3. +1
    -0
      static/testdata/test.txt

+ 10
- 4
static/static.go View File

@ -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
- 0
static/static_test.go View 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
- 0
static/testdata/test.txt View File

@ -0,0 +1 @@
Hello World

Loading…
Cancel
Save