webserver with random image serving

This commit is contained in:
Mike Bloy 2022-05-08 21:43:33 -05:00
parent 2b63bdecf4
commit 0eb6c10550
3 changed files with 55 additions and 5 deletions

View File

@ -62,5 +62,4 @@ func initConfig() {
os.Exit(1) os.Exit(1)
} }
} }
fmt.Println(viper.AllSettings())
} }

47
web/handlers.go Normal file
View File

@ -0,0 +1,47 @@
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)
}

View File

@ -3,7 +3,6 @@ package web
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"os"
"github.com/spf13/viper" "github.com/spf13/viper"
"go.uber.org/zap" "go.uber.org/zap"
@ -23,11 +22,16 @@ func Run(rootLogger *zap.Logger, exitch chan bool) {
config.logger = rootLogger.Named("web") config.logger = rootLogger.Named("web")
config.port = viper.GetInt("webserver_port") config.port = viper.GetInt("webserver_port")
config.imageDir = viper.GetString("image_dir") config.imageDir = viper.GetString("image_dir")
addr := fmt.Sprintf(":%d", config.port)
http.Handle("/", http.FileServer(http.FS(os.DirFS(".")))) http.Handle("/img/", http.StripPrefix("/img", imageHandler()))
http.HandleFunc("/randimg/", randomImageFunc)
var logger = config.logger.Sugar() var logger = config.logger.Sugar()
logger.Infow("Webserver startup", "port", config.port) logger.Infow("Webserver startup",
"port", config.port,
"imageDir", config.imageDir)
addr := fmt.Sprintf(":%d", config.port)
if err := http.ListenAndServe(addr, nil); err != nil { if err := http.ListenAndServe(addr, nil); err != nil {
logger.Errorf("Webserver fatal error: %s", err) logger.Errorf("Webserver fatal error: %s", err)