use /api/random endpoint for fetching images

This commit is contained in:
raf 2023-10-27 10:30:13 +03:00
parent 05642cb93b
commit 493e3972a2
No known key found for this signature in database
GPG key ID: 02D1DD3FA08B6B29

119
main.go
View file

@ -9,7 +9,6 @@ import (
"math/rand" "math/rand"
"net/http" "net/http"
"os" "os"
"path/filepath"
"strconv" "strconv"
"time" "time"
@ -33,32 +32,63 @@ func init() {
} }
func main() { func main() {
flag.StringVar(&port, "port", "3000", "Port to run the server on") viper.SetConfigName("config") // name of config file (without extension)
flag.Parse() viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".") // path to look for the config file in
// Initialize Viper for configuration management
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AutomaticEnv() // Allow environment variables to override config settings
// Read the configuration file (config.yaml in this example)
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading configuration file: %v", err) log.Fatalf("Error reading configuration file: %v", err)
} }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { port := viper.GetString("server.port")
images := getImages(r) // Call getImages with the request parameter flag.Parse()
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading configuration file: %v", err)
}
images = getImages()
http.HandleFunc("/", homeHandler)
http.HandleFunc("/api/id", idHandler)
http.HandleFunc("/api/list", listHandler)
http.HandleFunc("/api/random", randomHandler)
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid API path", http.StatusNotFound)
})
log.Println("Server started at port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func getImages() []string {
files, err := os.ReadDir("images/")
if err != nil {
logger.WithError(err).Fatal("Error reading images directory")
}
var images []string
for _, file := range files {
images = append(images, file.Name())
logger.Info("Loaded image:", file.Name())
}
return images
}
func sanitizeInput(input string) string {
return template.HTMLEscapeString(input)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<html><body><div style=\"display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-gap: 10px;\">") io.WriteString(w, "<html><body><div style=\"display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-gap: 10px;\">")
for i, image := range images { for i := range images {
io.WriteString(w, `<a href="/api/id?id=`+strconv.Itoa(i)+`">`) io.WriteString(w, `<a href="/api/id?id=`+strconv.Itoa(i)+`">`)
io.WriteString(w, `<img src="`+filepath.Base(image)+`" style="width: 100%; height: auto;"/>`) io.WriteString(w, `<img src="/api/id?id=`+strconv.Itoa(i)+`" style="width: 100%; height: auto;"/>`)
io.WriteString(w, `</a>`) io.WriteString(w, `</a>`)
} }
io.WriteString(w, "</div></body></html>") io.WriteString(w, "</div></body></html>")
}) }
http.HandleFunc("/api/id", func(w http.ResponseWriter, r *http.Request) { func idHandler(w http.ResponseWriter, r *http.Request) {
id := sanitizeInput(r.URL.Query().Get("id")) id := sanitizeInput(r.URL.Query().Get("id"))
if id == "" { if id == "" {
http.Error(w, "Missing id", http.StatusBadRequest) http.Error(w, "Missing id", http.StatusBadRequest)
@ -69,66 +99,29 @@ func main() {
http.Error(w, "Invalid id", http.StatusBadRequest) http.Error(w, "Invalid id", http.StatusBadRequest)
return return
} }
http.ServeFile(w, r, images[i]) http.ServeFile(w, r, "images/"+images[i])
}) }
http.HandleFunc("/api/list", func(w http.ResponseWriter, r *http.Request) { func listHandler(w http.ResponseWriter, r *http.Request) {
// Create a slice to store image information
imageList := []map[string]string{} imageList := []map[string]string{}
for i := range images {
for _, image := range images {
imageInfo := map[string]string{ imageInfo := map[string]string{
"image": image, "id": strconv.Itoa(i),
"url": "/" + filepath.Base(image), "url": "/api/id?id=" + strconv.Itoa(i),
} }
imageList = append(imageList, imageInfo) imageList = append(imageList, imageInfo)
} }
// Convert the slice to JSON
jsonData, err := json.Marshal(imageList) jsonData, err := json.Marshal(imageList)
if err != nil { if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
// Set the content type to JSON
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
// Write the JSON response
w.Write(jsonData) w.Write(jsonData)
}) }
http.HandleFunc("/api/random", func(w http.ResponseWriter, r *http.Request) { func randomHandler(w http.ResponseWriter, r *http.Request) {
// Reseed the random number generator to make it truly random on each request
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
i := rand.Intn(len(images)) i := rand.Intn(len(images))
http.ServeFile(w, r, images[i]) http.Redirect(w, r, "/api/id?id="+strconv.Itoa(i), http.StatusSeeOther)
})
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid API path", http.StatusNotFound)
})
log.Println("Server started at port", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func getImages(r *http.Request) []string {
files, err := os.ReadDir("images/")
if err != nil {
logger.WithError(err).Fatal("Error reading images directory")
}
var images []string
serverAddress := r.Host // Get the server address from the request
for _, file := range files {
imagePath := "http://" + serverAddress + "/images/" + file.Name()
images = append(images, imagePath)
logger.Info("Loaded image:", imagePath)
}
return images
}
func sanitizeInput(input string) string {
return template.HTMLEscapeString(input)
} }