From 1af34dfcf3e13f97e97f2423391e78f6a35aa332 Mon Sep 17 00:00:00 2001 From: grey Date: Thu, 13 Oct 2022 12:47:44 +0200 Subject: [PATCH] - add predictable / vanity ids - add / route --- soundr.go | 1 + webRoutes.go | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/soundr.go b/soundr.go index b64f051..d158cd7 100644 --- a/soundr.go +++ b/soundr.go @@ -90,6 +90,7 @@ func main() { http.HandleFunc("/v1/stopAll", handleStopAll) http.HandleFunc("/v1/current", handleCurrent) http.HandleFunc("/v1/list", handleListing) + http.HandleFunc("/", handleRoot) fmt.Println("Listening on port " + fmt.Sprint(configuration.Port)) log.Fatal(http.ListenAndServe(":"+fmt.Sprint(configuration.Port), nil)) diff --git a/webRoutes.go b/webRoutes.go index 2127c51..44b76cf 100644 --- a/webRoutes.go +++ b/webRoutes.go @@ -34,6 +34,8 @@ func handlePlay(w http.ResponseWriter, r *http.Request) { loopBool = true } + wantedId := r.URL.Query().Get("id") // Retrieve the id value from the query string, it's optional + t, err := os.Stat("./sounds/" + string(bytArr[:])) // Check if the file exists if errors.Is(err, os.ErrNotExist) { w.WriteHeader(400) @@ -60,7 +62,21 @@ func handlePlay(w http.ResponseWriter, r *http.Request) { return } - var currIndex = len(playbacks) // Create a new index for the playback + var currIndex = len(playbacks) // Create a new index for the playback + + if len(wantedId) > 0 { // If the id is set, check if it is already in use + id, err := strconv.Atoi(wantedId) + if err != nil { + fmt.Fprintf(w, "{\"status\":\"fail\", \"reason\":\"id is not a number\"}") + return + } + if _, ok := playbacks[id]; ok { + fmt.Fprintf(w, "{\"status\":\"fail\", \"reason\":\"id is already in use\"}") + return + } + currIndex = id + } + fmt.Fprintf(w, "{\"status\":\"ok\", \"id\":%d}", currIndex) // Return a JSON object to the user go PlaySound(string(bytArr[:]), currIndex, loopBool) // Play the sound @@ -267,3 +283,7 @@ func handleListing(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, string(j)) } } + +func handleRoot(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Soundr is running.") +}