From dc2729ff912050da5aaca643ba156d0bd936a8bf Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Mon, 30 Dec 2024 14:58:03 +0400 Subject: [PATCH] Changed logic of ScanDirectory() func. --- cmd/dwelling-files/main.go | 2 +- pkg/files/files.go | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/cmd/dwelling-files/main.go b/cmd/dwelling-files/main.go index e91c4b7..6362d65 100644 --- a/cmd/dwelling-files/main.go +++ b/cmd/dwelling-files/main.go @@ -100,7 +100,7 @@ func Index(w http.ResponseWriter, r *http.Request) { path += "/" } - entries, stats, err := files.ScanDirectory(*directoryPath+path, path) + entries, stats, err := files.ScanDirectory(*directoryPath, path) if err != nil { log.Println("Error directory scan:", err) http.Error(w, "Not found", http.StatusNotFound) diff --git a/pkg/files/files.go b/pkg/files/files.go index df9fc31..0ff61cb 100644 --- a/pkg/files/files.go +++ b/pkg/files/files.go @@ -22,8 +22,14 @@ type DirEntry struct { Size string } -func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStat, err error) { - dir, err := os.ReadDir(path) +// ScanDirectory returns entries of directory which is located by its relative +// path within a base directory. +// +// rel path should start/end with a / symbol. +func ScanDirectory(base, rel string) (entries []DirEntry, stats DirStat, err error) { + abs := base + rel + + dir, err := os.ReadDir(abs) if err != nil { return } @@ -37,7 +43,7 @@ func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStat, err var isDirLink bool if entry.Mode().Type()&os.ModeSymlink != 0 { - if slp, err := filepath.EvalSymlinks(filepath.Join(path, entry.Name())); err == nil { + if slp, err := filepath.EvalSymlinks(filepath.Join(abs, entry.Name())); err == nil { lStat, _ := os.Lstat(slp) isDirLink = lStat.IsDir() } @@ -54,7 +60,7 @@ func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStat, err } else { fileEntries = append(fileEntries, DirEntry{ Name: entry.Name(), - Link: "/file" + urlBase + url.PathEscape(entry.Name()), + Link: "/file" + rel + url.PathEscape(entry.Name()), Datetime: entry.ModTime(), Size: convertFileSize(entry.Size()), })