refactored code for easy of reading
started on spicy
This commit is contained in:
50
main.go
50
main.go
@@ -8,28 +8,40 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/files", func(w http.ResponseWriter, r *http.Request) {
|
||||
files, err := os.ReadDir("./static")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, f := range files {
|
||||
|
||||
name := f.Name()
|
||||
if strings.HasSuffix(name, ".jpg") || strings.HasSuffix(name, ".png") || strings.HasSuffix(name, ".gif") {
|
||||
// Serves index
|
||||
http.HandleFunc("/", index_handler)
|
||||
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
// Serves json for html to find file names
|
||||
http.HandleFunc("/files", files_handler)
|
||||
|
||||
json.NewEncoder(w).Encode(names)
|
||||
})
|
||||
|
||||
fs := http.FileServer(http.Dir("./static"))
|
||||
http.Handle("/", fs)
|
||||
// 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")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, f := range files {
|
||||
name := f.Name()
|
||||
if strings.HasSuffix(name, ".jpg") ||
|
||||
strings.HasSuffix(name, ".png") ||
|
||||
strings.HasSuffix(name, ".gif") {
|
||||
names = append(names, "/images/"+name)
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(names)
|
||||
}
|
||||
|
BIN
static/base.png
Normal file
BIN
static/base.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.4 KiB |
BIN
static/img1.jpg
BIN
static/img1.jpg
Binary file not shown.
Before Width: | Height: | Size: 491 KiB |
@@ -22,18 +22,17 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<img id="images" src="img1.jpg" alt="images">
|
||||
<img id="images" src="base.png" alt="images">
|
||||
<script>
|
||||
fetch("/files")
|
||||
.then(res => res.json())
|
||||
.then(files => {
|
||||
console.log(files);
|
||||
const images = files
|
||||
let index = 0;
|
||||
setInterval(() => {
|
||||
index = (index + 1) % images.length;
|
||||
document.getElementById("images").src = images[index];
|
||||
}, 10000);
|
||||
}, 1000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.2 MiB |
Reference in New Issue
Block a user