diff --git a/fs.go b/fs.go index 0703814..6175721 100644 --- a/fs.go +++ b/fs.go @@ -33,6 +33,7 @@ type FS struct { UseLocalFolder bool LocalFolderPrefix string HeaderHandler HeaderHandler + IndexFilenames []string } // NewFS creates a new instance of the http file system used for serving static files. @@ -51,13 +52,13 @@ func (fs *FS) ServeHTTP(w http.ResponseWriter, r *http.Request, info RoutingInfo } // search for file in static file system - file, filePath, err := fs.findFile(url) + file, err := fs.findFile(url) if err != nil { http.NotFound(w, r) return } // check, if the file is a folder - file, ok := fs.checkFolder(file, filePath) + file, ok := fs.checkFolder(file, url) if !ok { http.NotFound(w, r) return @@ -68,7 +69,7 @@ func (fs *FS) ServeHTTP(w http.ResponseWriter, r *http.Request, info RoutingInfo fs.serve(w, r, info, file) } -func (fs *FS) findFile(url string) (fs.File, string, error) { +func (fs *FS) findFile(url string) (fs.File, error) { // build file path filePath := path.Join(fs.FolderPrefix, url) filePath = strings.TrimPrefix(filePath, "/") @@ -83,7 +84,7 @@ func (fs *FS) findFile(url string) (fs.File, string, error) { file, err := os.Open(localFilePath) if err == nil { - return file, localFilePath, nil + return file, nil } } @@ -92,7 +93,7 @@ func (fs *FS) findFile(url string) (fs.File, string, error) { filePath = "." } file, err := fs.StaticFiles.Open(filePath) - return file, filePath, err + return file, err } func (fs *FS) checkFolder(file fs.File, url string) (fs.File, bool) { @@ -107,6 +108,14 @@ func (fs *FS) checkFolder(file fs.File, url string) (fs.File, bool) { // close folder handler (we don't need it anymore) _ = file.Close() + // check for index files + for _, indexFileName := range fs.IndexFilenames { + newFullPath := path.Join(url, indexFileName) + if newFile, err := fs.findFile(newFullPath); err == nil { + return newFile, true + } + } + return file, false } diff --git a/fs_test.go b/fs_test.go index 049acc8..7f79a72 100644 --- a/fs_test.go +++ b/fs_test.go @@ -156,6 +156,27 @@ func TestFSFolderLocal(t *testing.T) { } } +func TestFSFolderIndex(t *testing.T) { + // create new FS + fs := NewFS(&staticFiles) + fs.IndexFilenames = []string{"README.md"} + + // serve the request + tw := &testWriter{} + tr := &http.Request{ + Method: http.MethodHead, + URL: &url.URL{ + Path: "/", + }, + } + fs.ServeHTTP(tw, tr, RoutingInfo{}) + + // check data + if tw.statusCode != http.StatusOK { + t.Error("received invalid http status code", tw.statusCode) + } +} + func TestFSNotFound(t *testing.T) { // create new FS fs := NewFS(&staticFiles)