From 86e2ee9a2acb836a5d9da046657c5d9c8efab6fc Mon Sep 17 00:00:00 2001 From: Alice GG Date: Mon, 13 Nov 2023 15:35:17 +0100 Subject: [PATCH] Refactor cacheFolder to use filepath.WalkDir --- backend/browser/cache.go | 34 ++++++++++++++++++---------------- backend/browser/handlers.go | 1 + 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/backend/browser/cache.go b/backend/browser/cache.go index 649a407..b237778 100644 --- a/backend/browser/cache.go +++ b/backend/browser/cache.go @@ -3,8 +3,8 @@ package browser import ( "io/fs" "log" - "os" "path/filepath" + "strings" "sync" "github.com/rjeczalik/notify" @@ -37,24 +37,26 @@ func ResetCache() { // recursively initalizes the cache // we do not use filepath.Walk to avoid a mess with relative / absolute paths func cacheFolder(cache map[string]fs.FileInfo, path string) { - dirEntries, err := os.ReadDir(getAbsolutePath(path)) + rootPath := getAbsolutePath(path) + err := filepath.WalkDir( + rootPath, + func(path string, dirEntry fs.DirEntry, err error) error { + relativePath := strings.TrimPrefix(path, rootPath) + if relativePath == "" { + return nil + } + fileInfo, err := dirEntry.Info() + if err != nil { + return err + } + + cache[relativePath] = fileInfo + return nil + }, + ) if err != nil { log.Panicf("Error while refreshing cache: %s", err.Error()) } - - for _, dirEntry := range dirEntries { - relativePath := filepath.Clean(path + dirEntry.Name()) - fileInfo, err := dirEntry.Info() - if err != nil { - log.Panicf("Error while refreshing cache: %s", err.Error()) - } - - cache[relativePath] = fileInfo - - if dirEntry.IsDir() { - cacheFolder(cache, relativePath+"/") - } - } } // refreshes the cache on data dir changes diff --git a/backend/browser/handlers.go b/backend/browser/handlers.go index 234f688..0e2f545 100644 --- a/backend/browser/handlers.go +++ b/backend/browser/handlers.go @@ -23,6 +23,7 @@ func StreamFile(c *gin.Context) { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "err": "Failed to stat file", }) + return } if dir {