First attempt

This commit is contained in:
Seednode 2022-09-08 10:57:59 -05:00
parent 3d76fcd889
commit 7ae3c72697
3 changed files with 82 additions and 2 deletions

72
cmd/files.go Normal file
View File

@ -0,0 +1,72 @@
/*
Copyright © 2022 Seednode <seednode@seedno.de>
*/
package cmd
import (
"io/fs"
"math/rand"
"os"
"path/filepath"
"time"
)
func pickFile(fileList []fs.DirEntry) string {
rand.Seed(time.Now().Unix())
isFile := false
var fileName string
for isFile == false {
file := fileList[rand.Intn(len(fileList))]
if file.IsDir() == false {
isFile = true
fileName = file.Name()
}
}
return fileName
}
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) []fs.DirEntry {
fileList, err := os.ReadDir(path)
if err != nil {
panic(err)
}
return fileList
}
func getFile(args []string) (string, string) {
fileList := []fs.DirEntry{}
for i := 0; i < len(args); i++ {
f := getFiles(args[i])
fileList = append(fileList, f...)
}
fileName := pickFile(fileList)
filePath, err := filepath.Abs(fileName)
if err != nil {
panic(err)
}
return fileName, filePath
}

View File

@ -17,8 +17,9 @@ var Verbose bool
var rootCmd = &cobra.Command{
Use: "roulette <path1> [path2] ... [pathN]",
Short: "Serves random images from the specified directories.",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
ServePage()
ServePage(args)
},
Version: Version,
}

View File

@ -9,6 +9,7 @@ import (
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
)
@ -123,7 +124,13 @@ func servePageHandler() http.HandlerFunc {
func doNothing(http.ResponseWriter, *http.Request) {}
func ServePage() {
func ServePage(args []string) {
fileName, filePath := getFile(args)
fmt.Println(fileName)
fmt.Println(filePath)
os.Exit(0)
defer HandleExit()
http.HandleFunc("/", servePageHandler())