72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package files
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"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
|
|
}
|
|
|
|
func ScanDirectory(path, urlBase string) (entries []DirEntry, stats DirStats, err error) {
|
|
var dirEntries []DirEntry = make([]DirEntry, 0)
|
|
var fileEntries []DirEntry = make([]DirEntry, 0)
|
|
var totalFilesSize int64 = 0
|
|
|
|
dir, err := ioutil.ReadDir(path)
|
|
for _, entry := range dir {
|
|
|
|
var isDirLink bool
|
|
if entry.Mode().Type().String()[0] == 'L' {
|
|
if slp, err := filepath.EvalSymlinks(filepath.Join(path, entry.Name())); err == nil {
|
|
lStat, _ := os.Lstat(slp)
|
|
isDirLink = lStat.IsDir()
|
|
}
|
|
}
|
|
|
|
if entry.IsDir() || isDirLink {
|
|
dirEntries = append(dirEntries, DirEntry{
|
|
Name: entry.Name(),
|
|
Link: url.PathEscape(entry.Name()) + "/",
|
|
Datetime: entry.ModTime(),
|
|
Size: "DIR",
|
|
})
|
|
stats.Directories++
|
|
} else {
|
|
_, _, sz := convertFileSize(entry.Size())
|
|
fileEntries = append(fileEntries, DirEntry{
|
|
Name: entry.Name(),
|
|
Link: "/file" + urlBase + url.PathEscape(entry.Name()),
|
|
Datetime: entry.ModTime(),
|
|
Size: sz,
|
|
})
|
|
|
|
totalFilesSize += entry.Size()
|
|
stats.Files++
|
|
}
|
|
}
|
|
|
|
_, _, sz := convertFileSize(totalFilesSize)
|
|
stats.FilesSize = sz
|
|
|
|
entries = append(entries, dirEntries...)
|
|
entries = append(entries, fileEntries...)
|
|
|
|
return
|
|
}
|