feat: Adding audio player + music to play

This commit is contained in:
gauvainboiche
2026-10-25 22:35:53 +01:00
parent 7a525d084a
commit dd4714f499
39 changed files with 850 additions and 81 deletions
+59 -3
View File
@@ -1,10 +1,14 @@
package main
import (
"encoding/json"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"countrygame/web"
)
@@ -24,19 +28,31 @@ func main() {
os.Exit(0)
}
// Background music: .mp3 files read live from this folder, so adding a track needs no rebuild.
musicDir := os.Getenv("MUSIC_DIR")
if musicDir == "" {
musicDir = "music"
}
root, err := fs.Sub(web.Files, ".")
if err != nil {
log.Fatal(err)
}
log.Printf("country game listening on :%s (music folder %q)", port, musicDir)
log.Fatal(http.ListenAndServe(":"+port, newMux(root, musicDir)))
}
// newMux serves the embedded game, /healthz, and the music folder under /music/.
func newMux(root fs.FS, musicDir string) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
mux.HandleFunc("/music/index.json", musicIndex(musicDir))
mux.Handle("/music/", http.StripPrefix("/music/", noCache(http.FileServer(noListing{http.Dir(musicDir)}))))
mux.Handle("/", noCache(http.FileServer(http.FS(root))))
log.Printf("country game listening on :%s", port)
log.Fatal(http.ListenAndServe(":"+port, mux))
return mux
}
// noCache keeps iteration simple: data and scripts are always revalidated.
@@ -46,3 +62,43 @@ func noCache(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
})
}
// noListing hides directory listings and dot files: only the tracks themselves are served.
type noListing struct{ fs http.FileSystem }
func (n noListing) Open(name string) (http.File, error) {
if strings.Contains(filepath.Base(name), "..") || strings.HasPrefix(filepath.Base(name), ".") {
return nil, os.ErrNotExist
}
f, err := n.fs.Open(name)
if err != nil {
return nil, err
}
if info, err := f.Stat(); err != nil || info.IsDir() {
f.Close()
return nil, os.ErrNotExist
}
return f, nil
}
// musicIndex lists the playable tracks: non-empty .mp3 files (the empty placeholder is skipped), sorted by name.
// A missing folder is not an error: the game simply shows an empty tape deck.
func musicIndex(dir string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tracks := []string{}
entries, _ := os.ReadDir(dir)
for _, e := range entries {
name := e.Name()
if e.IsDir() || strings.HasPrefix(name, ".") || !strings.EqualFold(filepath.Ext(name), ".mp3") {
continue
}
if info, err := e.Info(); err == nil && info.Size() > 0 {
tracks = append(tracks, name)
}
}
sort.Strings(tracks)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
json.NewEncoder(w).Encode(map[string]any{"tracks": tracks})
}
}