feat: Adding audio player + music to play
This commit is contained in:
+59
-3
@@ -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})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func musicServer(t *testing.T) (*httptest.Server, string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
write := func(name, content string) {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("b_second.MP3", "not really audio, but not empty")
|
||||
write("a_first.mp3", "0123456789")
|
||||
write("placeholder.mp3", "") // the empty placeholder must not be offered
|
||||
write("notes.txt", "hello")
|
||||
write(".hidden.mp3", "secret")
|
||||
if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
site := fstest.MapFS{"index.html": {Data: []byte("<h1>game</h1>")}}
|
||||
return httptest.NewServer(newMux(site, dir)), dir
|
||||
}
|
||||
|
||||
func get(t *testing.T, url string, header ...string) (*http.Response, string) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
for i := 0; i+1 < len(header); i += 2 {
|
||||
req.Header.Set(header[i], header[i+1])
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
buf := make([]byte, 4096)
|
||||
n, _ := resp.Body.Read(buf)
|
||||
return resp, string(buf[:n])
|
||||
}
|
||||
|
||||
func TestMusicFolder(t *testing.T) {
|
||||
srv, _ := musicServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
// the index offers only real, non-empty mp3 files, sorted
|
||||
resp, body := get(t, srv.URL+"/music/index.json")
|
||||
var idx struct{ Tracks []string }
|
||||
if err := json.Unmarshal([]byte(body), &idx); err != nil {
|
||||
t.Fatalf("index.json: %v (%s)", err, body)
|
||||
}
|
||||
if want := []string{"a_first.mp3", "b_second.MP3"}; !reflect.DeepEqual(idx.Tracks, want) {
|
||||
t.Errorf("tracks = %v, want %v", idx.Tracks, want)
|
||||
}
|
||||
if resp.Header.Get("Cache-Control") != "no-store" {
|
||||
t.Error("the index must not be cached: tracks are added without a rebuild")
|
||||
}
|
||||
|
||||
// a track is served, and byte ranges work (the browser needs them to seek)
|
||||
if r, b := get(t, srv.URL+"/music/a_first.mp3"); r.StatusCode != 200 || b != "0123456789" {
|
||||
t.Errorf("track: %d %q", r.StatusCode, b)
|
||||
}
|
||||
if r, b := get(t, srv.URL+"/music/a_first.mp3", "Range", "bytes=2-4"); r.StatusCode != 206 || b != "234" {
|
||||
t.Errorf("range: %d %q", r.StatusCode, b)
|
||||
}
|
||||
|
||||
// nothing else leaks: no listing, no dot files, no sub folders, no way out of the folder
|
||||
for _, path := range []string{"/music/", "/music/.hidden.mp3", "/music/sub", "/music/..%2Fmain.go", "/music/%2e%2e/main.go"} {
|
||||
if r, _ := get(t, srv.URL+path); r.StatusCode == 200 {
|
||||
t.Errorf("%s must not be served", path)
|
||||
}
|
||||
}
|
||||
// the game itself is still served
|
||||
if r, b := get(t, srv.URL+"/"); r.StatusCode != 200 || b != "<h1>game</h1>" {
|
||||
t.Errorf("site: %d %q", r.StatusCode, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMusicFolderMissing(t *testing.T) {
|
||||
srv := httptest.NewServer(newMux(fstest.MapFS{}, filepath.Join(t.TempDir(), "nope")))
|
||||
defer srv.Close()
|
||||
resp, body := get(t, srv.URL+"/music/index.json")
|
||||
if resp.StatusCode != 200 || body != "{\"tracks\":[]}\n" {
|
||||
t.Errorf("a missing music folder should give an empty list, got %d %q", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user