webserver with random image serving
This commit is contained in:
parent
2b63bdecf4
commit
0eb6c10550
@ -62,5 +62,4 @@ func initConfig() {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
fmt.Println(viper.AllSettings())
|
||||
}
|
||||
|
||||
47
web/handlers.go
Normal file
47
web/handlers.go
Normal 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)
|
||||
}
|
||||
@ -3,7 +3,6 @@ package web
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/zap"
|
||||
@ -23,11 +22,16 @@ func Run(rootLogger *zap.Logger, exitch chan bool) {
|
||||
config.logger = rootLogger.Named("web")
|
||||
config.port = viper.GetInt("webserver_port")
|
||||
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()
|
||||
|
||||
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 {
|
||||
logger.Errorf("Webserver fatal error: %s", err)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user