Im developing a small IOT device for my home running in a PI. The server (running in Go) hosts a web interface which should be able to do tasks in realtime (eg. pressing a button should change the sound output by the pi without reloading the page)
Im trying to send a post request from my web interface to the pi so that the requests can be handled in realtime by the server application. I want to do this without reloading the page. I used Javascript fetch to do this:
document.getElementById("buttons_form").addEventListener("submit", function(e) {
e.preventDefault();
const formData = new FormData(this); // IDEALLY this would be done without a form
fetch("/change-sound", { method: "POST", body: formData });
My server responds to the request. When using fmt.Println(r.Form)
, the output is just map[]
. Request.Body
gives &{0xc000298060 <nil> <nil> false true {0 0} false false false 0x69cd20}
. This is the rough go code I have at the moment:
func ChangeSound(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
return
}
err := r.ParseForm()
if err != nil {
log.Fatal(err)
}
fmt.Println(r.Form)
}
When I use the form normally instead of sending the post request via javascript, the request form in go gives the expected map with all of the form variables (but of course there is no way to do this without reloading, plus I want to have sliders etc that would work in realtime as well which a form would not work for)
How can I send an arbitrary post request using javascript that will be able to be parsed by the server? I'm fairly new to both go and web-development.