1
0
dwelling-files/pkg/files/files.go

62 lines
1.2 KiB
Go
Raw Normal View History

2022-06-27 04:38:09 +04:00
package files
import (
2022-06-27 22:50:33 +04:00
"io/ioutil"
2022-06-27 04:38:09 +04:00
"net/url"
"time"
)
const FileDateFormat = "2006-01-02 15:04:05 MST"
type DirStats struct {
Files int64
FilesSize string
Directories int64
}
type DirEntry struct {
Name string
Link string
Datetime time.Time
Size string
}
2022-06-27 22:50:33 +04:00
func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStats, err error) {
2022-06-27 04:38:09 +04:00
var dirEntries []DirEntry = make([]DirEntry, 0)
var fileEntries []DirEntry = make([]DirEntry, 0)
var totalFilesSize int64 = 0
2022-06-27 22:50:33 +04:00
dir, err := ioutil.ReadDir(path)
for _, entry := range dir {
2022-06-27 04:38:09 +04:00
2022-06-27 22:50:33 +04:00
if entry.IsDir() {
2022-06-27 04:38:09 +04:00
dirEntries = append(dirEntries, DirEntry{
2022-06-27 22:50:33 +04:00
Name: entry.Name(),
Link: url.PathEscape(entry.Name()) + "/",
Datetime: entry.ModTime(),
2022-06-27 04:38:09 +04:00
Size: "DIR",
})
stats.Directories++
} else {
2022-06-27 22:50:33 +04:00
_, _, sz := convertFileSize(entry.Size())
2022-06-27 04:38:09 +04:00
fileEntries = append(fileEntries, DirEntry{
2022-06-27 22:50:33 +04:00
Name: entry.Name(),
Link: "/file" + urlBase + url.PathEscape(entry.Name()),
Datetime: entry.ModTime(),
2022-06-27 04:38:09 +04:00
Size: sz,
})
2022-06-27 22:50:33 +04:00
totalFilesSize += entry.Size()
2022-06-27 04:38:09 +04:00
stats.Files++
}
}
_, _, sz := convertFileSize(totalFilesSize)
stats.FilesSize = sz
entries = append(entries, dirEntries...)
entries = append(entries, fileEntries...)
return
}