Skip to content
This repository has been archived by the owner on Mar 31, 2020. It is now read-only.

Commit

Permalink
Call NotFound on folder listing (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
abeltay authored Feb 5, 2018
1 parent d999fc3 commit becaa02
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions web/fileserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit becaa02

Please sign in to comment.