refactored code for easy of reading

started on spicy
This commit is contained in:
2025-08-16 12:38:58 +02:00
parent 84bc80d921
commit 140a129114
5 changed files with 33 additions and 22 deletions

38
main.go
View File

@@ -8,7 +8,25 @@ import (
) )
func main() { func main() {
http.HandleFunc("/files", func(w http.ResponseWriter, r *http.Request) {
// Serves index
http.HandleFunc("/", index_handler)
// Serves json for html to find file names
http.HandleFunc("/files", files_handler)
// Serves images
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./static"))))
// Serves what ever the user is requesting based on above urls
http.ListenAndServe(":8080", nil)
}
func index_handler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}
func files_handler(w http.ResponseWriter, r *http.Request) {
files, err := os.ReadDir("./static") files, err := os.ReadDir("./static")
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
@@ -16,20 +34,14 @@ func main() {
} }
var names []string var names []string
for _, f := range files { for _, f := range files {
name := f.Name() name := f.Name()
if strings.HasSuffix(name, ".jpg") || strings.HasSuffix(name, ".png") || strings.HasSuffix(name, ".gif") { if strings.HasSuffix(name, ".jpg") ||
strings.HasSuffix(name, ".png") ||
strings.HasSuffix(name, ".gif") {
names = append(names, "/images/"+name)
}
}
names = append(names, name)
}
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(names) json.NewEncoder(w).Encode(names)
})
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.ListenAndServe(":8080", nil)
} }

BIN
static/base.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 491 KiB

View File

@@ -22,18 +22,17 @@
</head> </head>
<body> <body>
<img id="images" src="img1.jpg" alt="images"> <img id="images" src="base.png" alt="images">
<script> <script>
fetch("/files") fetch("/files")
.then(res => res.json()) .then(res => res.json())
.then(files => { .then(files => {
console.log(files);
const images = files const images = files
let index = 0; let index = 0;
setInterval(() => { setInterval(() => {
index = (index + 1) % images.length; index = (index + 1) % images.length;
document.getElementById("images").src = images[index]; document.getElementById("images").src = images[index];
}, 10000); }, 1000);
}); });
</script> </script>
</body> </body>

View File

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.2 MiB