From 3707690aa02277812e65acdb10c55524e1d8080d Mon Sep 17 00:00:00 2001 From: soedar Date: Thu, 21 Dec 2017 10:13:25 +0800 Subject: [PATCH] Add file server which disables directory listing (#7) --- web/fileserver.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 web/fileserver.go diff --git a/web/fileserver.go b/web/fileserver.go new file mode 100644 index 0000000..c8a3bca --- /dev/null +++ b/web/fileserver.go @@ -0,0 +1,32 @@ +package web + +import ( + "net/http" + "os" +) + +// FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root. +// This implementation will always returns 404 Not Found if the request is a directory, and will not serve `index.html`. +// https://groups.google.com/d/msg/golang-nuts/bStLPdIVM6w/wSKqNoaSji8J +func FileServer(root http.Dir) http.Handler { + return http.FileServer(justFilesFilesystem{root}) +} + +type justFilesFilesystem struct { + fs http.FileSystem +} + +func (fs justFilesFilesystem) Open(name string) (http.File, error) { + f, err := fs.fs.Open(name) + + if err != nil { + return nil, err + } + + stat, err := f.Stat() + if stat.IsDir() { + return nil, os.ErrNotExist + } + + return f, nil +}