package web import ( "fmt" "io/fs" "math/rand" "net/http" "os" ) func imageHandler() http.Handler { fs := http.FS(os.DirFS(config.imageDir)) hfs := http.FileServer(fs) return hfs } func chooseRandomFile(imageDir string) (filepath string, err error) { validEntries := make([]string, 0) log := config.logger.Sugar() err = fs.WalkDir(os.DirFS(imageDir), ".", func(path string, d fs.DirEntry, err error) error { if err != nil { log.Errorw("Error walking directory", "imageDir", imageDir, "error", err) return err } if d.Type().IsRegular() { validEntries = append(validEntries, fmt.Sprintf("%s/%s", imageDir, d.Name())) } return nil }) chosen := rand.Intn(len(validEntries)) filepath = validEntries[chosen] return } func randomImageFunc(w http.ResponseWriter, r *http.Request) { log := config.logger.Sugar() path, err := chooseRandomFile(config.imageDir) if err != nil { log.Errorw("Couldn't choose a random file", "error", err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "Error selecting a file.") return } log.Infow("serving image file", "path", path) http.ServeFile(w, r, path) }