Skip to content

Commit

Permalink
removing dir listings from fs
Browse files Browse the repository at this point in the history
  • Loading branch information
estivate committed Jan 27, 2021
1 parent 2c88760 commit 21008f9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
5 changes: 3 additions & 2 deletions badorigin.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@ func (s *Servers) LaunchServers() {
r.PathPrefix("/error/{code}/{message}").HandlerFunc(errorHandler)

// Static File server
fs := http.FileServer(http.Dir(s.ContentRoot))
r.PathPrefix("/").Handler(fs)
// fs := http.FileServer(NoDirectoryListingFS{http.Dir(s.ContentRoot)})
// r.PathPrefix("/").Handler(fs)
r.PathPrefix("/").Handler(NoDirFS(s.ContentRoot, ""))

// middleware
r.Use(logging)
Expand Down
34 changes: 34 additions & 0 deletions filesystem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package badorigin

import (
"net/http"
"strings"
)

// NoDirFS creates a handler for a File Server that doesn't
// return directory listings.
func NoDirFS(root_dir, path string) http.HandlerFunc {
fs := http.FileServer(CustomFS{http.Dir(root_dir)})
return http.StripPrefix(strings.TrimRight(path, "/"), fs).ServeHTTP
}

type CustomFS struct {
fs http.FileSystem
}

func (fs CustomFS) Open(path string) (http.File, error) {
f, err := fs.fs.Open(path)
if err != nil {
return nil, err
}

s, err := f.Stat()
if s.IsDir() {
index := strings.TrimSuffix(path, "/") + "/index.html"
if _, err := fs.fs.Open(index); err != nil {
return nil, err
}
}

return f, nil
}

0 comments on commit 21008f9

Please sign in to comment.