diff --git a/middleware/filesystem/README.md b/middleware/filesystem/README.md index ddf1b4c883..52e0f8bbc8 100644 --- a/middleware/filesystem/README.md +++ b/middleware/filesystem/README.md @@ -44,7 +44,7 @@ Then create a Fiber app with `app := fiber.New()`. ```go // Provide a minimal config app.Use(filesystem.New(filesystem.Config{ - Root: http.Dir("./assets") + Root: http.Dir("./assets"), })) // Or extend your config for customization @@ -96,7 +96,7 @@ func main() { // `http:///static/static/image.png`. app.Use("/static", filesystem.New(filesystem.Config{ Root: http.FS(embedDirStatic), - PathPrefix: "static" + PathPrefix: "static", Browse: true, })) diff --git a/middleware/filesystem/filesystem.go b/middleware/filesystem/filesystem.go index 88eb79958b..73b9793eca 100644 --- a/middleware/filesystem/filesystem.go +++ b/middleware/filesystem/filesystem.go @@ -8,6 +8,7 @@ import ( "sync" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/utils" ) // Config defines the config for middleware. @@ -131,6 +132,9 @@ func New(config ...Config) fiber.Handler { stat os.FileInfo ) + if len(path) > 1 { + path = utils.TrimRight(path, '/') + } file, err = cfg.Root.Open(path) if err != nil && os.IsNotExist(err) && cfg.NotFoundFile != "" { file, err = cfg.Root.Open(cfg.NotFoundFile) @@ -149,7 +153,7 @@ func New(config ...Config) fiber.Handler { // Serve index if path is directory if stat.IsDir() { - indexPath := strings.TrimSuffix(path, "/") + cfg.Index + indexPath := utils.TrimRight(path, '/') + cfg.Index index, err := cfg.Root.Open(indexPath) if err == nil { indexStat, err := index.Stat() @@ -222,7 +226,7 @@ func SendFile(c *fiber.Ctx, fs http.FileSystem, path string) (err error) { // Serve index if path is directory if stat.IsDir() { - indexPath := strings.TrimSuffix(path, "/") + ConfigDefault.Index + indexPath := utils.TrimRight(path, '/') + ConfigDefault.Index index, err := fs.Open(indexPath) if err == nil { indexStat, err := index.Stat() diff --git a/middleware/filesystem/filesystem_test.go b/middleware/filesystem/filesystem_test.go index fb71d40329..0605fc151d 100644 --- a/middleware/filesystem/filesystem_test.go +++ b/middleware/filesystem/filesystem_test.go @@ -89,6 +89,12 @@ func Test_FileSystem(t *testing.T) { statusCode: 200, contentType: "text/html", }, + { + name: "Should list the directory contents", + url: "/dir/img/", + statusCode: 200, + contentType: "text/html", + }, { name: "Should be returns status 200", url: "/dir/img/fiber.png", diff --git a/middleware/filesystem/utils.go b/middleware/filesystem/utils.go index 3d20554be2..386c13e389 100644 --- a/middleware/filesystem/utils.go +++ b/middleware/filesystem/utils.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/utils" ) func getFileExtension(path string) string { @@ -40,7 +41,7 @@ func dirList(c *fiber.Ctx, f http.File) error { fmt.Fprint(c, "