hasshelper/web/handlers.go
2022-05-27 18:41:01 -05:00

61 lines
1.5 KiB
Go

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().Str("imageDir", imageDir).Logger()
err = fs.WalkDir(os.DirFS(imageDir), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Error().Err(err).Msg("Error walking directory")
return err
}
if ctxErr := ctx.Err(); ctxErr != nil {
log.Error().Err(ctxErr).Msg("Context closed while walking directory")
return ctxErr
}
if d.Type().IsRegular() {
filename := fmt.Sprintf("%s%c%s", imageDir, os.PathSeparator, d.Name())
log.Debug().Str("filename", filename).Msg("file scan")
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().Err(err).Msg("Couldn't choose a random file")
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Info().Str("imageFile", path).Msg("random image served")
http.ServeFile(w, r, path)
}