package web import ( "fmt" "io/fs" "math/rand" "net/http" "os" "golang.org/x/net/context" ) func imageHandler() http.Handler { fs := http.FS(os.DirFS(config.imageDir)) hfs := http.FileServer(fs) return hfs } func chooseRandomFile(ctx context.Context, imageDir string) (filepath string, err error) { validEntries := make([]string, 0) log := config.logger.With("imageDir", imageDir) err = fs.WalkDir( os.DirFS(imageDir), ".", func(path string, d fs.DirEntry, err error) error { if err != nil { log.Error("Error walking directory", "err", err) return err } if ctxErr := ctx.Err(); ctxErr != nil { log.Error("Context closed while walking directory", "err", ctxErr) return ctxErr } if d.Type().IsRegular() { filename := fmt.Sprintf("%s%c%s", imageDir, os.PathSeparator, d.Name()) log.Debug("file scan", filename, "filename") validEntries = append(validEntries, filename) } return nil }) if err != nil { return } if ctxErr := ctx.Err(); ctxErr != nil { err = ctxErr return } chosen := rand.Intn(len(validEntries)) filepath = validEntries[chosen] return } func randomImageFunc(w http.ResponseWriter, r *http.Request) { log := config.logger path, err := chooseRandomFile(r.Context(), config.imageDir) if err != nil { log.Error("Couldn't choose a random file", "err", err) w.WriteHeader(http.StatusInternalServerError) return } log.Info("random image served", "imagefile", path) http.ServeFile(w, r, path) }