From becaa021ba47725e142bedfae9b7fbd576008a97 Mon Sep 17 00:00:00 2001 From: abeltay Date: Mon, 5 Feb 2018 13:27:28 +0800 Subject: [PATCH] Call NotFound on folder listing (#11) --- web/fileserver.go | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/web/fileserver.go b/web/fileserver.go index d7415da..a371898 100644 --- a/web/fileserver.go +++ b/web/fileserver.go @@ -6,29 +6,42 @@ import ( "strings" ) -// FileServerHandler creates a file server that serves files from from a "Root" folder. -// It will call "NotFound" HandlerFunc if the path contains '..' or if the file cannot be found on the system. -type FileServerHandler struct { +type fileHandler struct { Root string NotFound http.HandlerFunc } -// FileServer creates a FileServer that returns http.NotFound if the file cannot be found on the system -func FileServer(root http.Dir) http.Handler { - return FileServerHandler{ - Root: string(root), +// FileServer is a FileServerHandler with the NotFound handler set to http.NotFound. +func FileServer(root string) http.Handler { + return fileHandler{ + Root: root, NotFound: http.NotFound, } } -func (f FileServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { +// FileServerHandler creates a file server that serves files from from a "Root" folder. +// It will call "NotFound" HandlerFunc if the file cannot be found on the system. +// In the event where the path is a directory, it will not redirect and instead call "NotFound" HandlerFunc. +func FileServerHandler(root string, notFound http.HandlerFunc) http.Handler { + if notFound == nil { + return FileServer(root) + } + return fileHandler{ + Root: root, + NotFound: notFound, + } +} + +func (h fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if containsDotDot(r.URL.Path) { - f.NotFound(w, r) + h.NotFound(w, r) return } - name := f.Root + r.URL.Path - if _, err := os.Stat(name); os.IsNotExist(err) { - f.NotFound(w, r) + + name := h.Root + r.URL.Path + info, err := os.Stat(name) + if os.IsNotExist(err) || info.IsDir() { + h.NotFound(w, r) return } http.ServeFile(w, r, name)