Confirmed recursive and nonrecursive functions both work as expected

This commit is contained in:
Seednode 2022-09-08 13:12:50 -05:00
parent eee4917322
commit d052fd6af9
2 changed files with 25 additions and 30 deletions

View File

@ -5,75 +5,66 @@ Copyright © 2022 Seednode <seednode@seedno.de>
package cmd
import (
"fmt"
"math/rand"
"os"
"path/filepath"
"time"
)
func getRandomFile(fileList []os.DirEntry) string {
rand.Seed(time.Now().Unix())
file := fileList[rand.Intn(len(fileList))].Name()
absolutePath, err := filepath.Abs(file)
if err != nil {
panic(err)
}
return absolutePath
}
func getFiles(path string) ([]string, error) {
fileList, err := os.ReadDir(path)
var paths []string
return fileList, err
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
if info.IsDir() && p != path {
return filepath.SkipDir
} else {
paths = append(paths, p)
}
return err
})
if err != nil {
return nil, err
}
return paths, nil
}
func getFilesRecursive(path string) ([]string, error) {
var paths []string
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
// if strings.HasPrefix(info.Name(), ".") {
// if info.IsDir() {
// return filepath.SkipDir
// }
// return err
// }
if !info.IsDir() {
paths = append(paths, p)
}
return err
})
rand.Seed(time.Now().Unix())
file := paths[rand.Intn(len(paths))]
fmt.Println(file)
return paths, err
if err != nil {
return nil, err
}
func getFileList(args []string) []string {
return paths, nil
}
func getFileList(args []string) ([]string, error) {
fileList := []string{}
for i := 0; i < len(args); i++ {
if Recursive {
f, err := getFilesRecursive(args[i])
if err != nil {
panic(err)
return nil, err
}
fileList = append(fileList, f...)
} else {
f, err := getFiles(args[i])
if err != nil {
panic(err)
return nil, err
}
fileList = append(fileList, f...)
}
}
return fileList
return fileList, nil
}
func pickFile(fileList []string) (string, string) {

View File

@ -126,7 +126,11 @@ func doNothing(http.ResponseWriter, *http.Request) {}
func ServePage(args []string) {
fileList := getFileList(args)
fileList, err := getFileList(args)
if err != nil {
panic(err)
}
fileName, filePath := pickFile(fileList)
fmt.Println(fileName)
fmt.Println(filePath)