javascriptgo

Fetch Data from FormData in Javascript and handle in Golang


i'm trying to fetch some data from a HTML Webpage via Javascript to my Golang Webserver. But the Data does'nt seem to be received there.

This is my Javascript Function, which is called, when selecting something in my dropdown menu of my webpage:

async function onDataFormatSelect(dataFormat) 
    {
      console.log('Change DataFormat', dataFormat);
      let formDataSelect = new FormData();
      formDataSelect.append("cmd", "change");
      const fetchoptions  = {
        method: 'POST',
        body: formDataSelect,
      };

      let r = await fetch('/myURL', fetchoptions);
      console.log('HTTP response code.', r.status);
      for (var pair of formDataSelect.entries()) {
        console.log(pair[0]+ ', ' + pair[1]); 
      }
    }

In SetupRoutes() in my Go Webserver, the URL gets an Handler:

    http.HandleFunc("/myURL", urlHandler)

This is my Handler:

func urlHandler(w http.ResponseWriter, r *http.Request) {
    

    if r.Method == "POST" {
        r.ParseForm()

        topicName := r.FormValue("topicName")
        cmd := r.FormValue("cmd")
        log.Println("action: " + cmd)
        switch cmd {
        ...
        case "change": //Change DataFormat of Topic
            log.Println("cmd is " + cmd)
            newDataFormat := r.FormValue("dataFormat")
            //Call another function
        default:
            log.Println("unknown command: " + cmd)
        }

    } else {
        log.Println("using wrong method (GET)")
    }

    http.Redirect(w, r, appdata.Status.ProxyRedirect, http.StatusMovedPermanently)
}

The Output of Javascript is correct. The FormDataSelect is filled correctly, but in Go the "cmd" is not there. Somehow in another Function with the same setup everything is working correctly.

Can you help me or do you have any Workaround for me beside using XMLHttpRequest?


Solution

  • FormData objects are designed to support posting files so they always send multipart requests.

    See the documentation for Go's http module.

    You're using parseForm which says:

    when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value

    You need to use ParseMultipartForm instead.