Access HTTP POST parameters in Go

I encountered a small problem when trying to use POST to the Go backendAxiosBut I cannot get the parameters being sent.

I am doing this:

func handleReq(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		panic(err)
	}
	v := req.Form
	owner := req.Form.Get("owner")
	name := req.Form.Get("name")
    //...
}

But the two parameters I am looking for are not available. why?

Turns out I assumed that Axios sent the parameters using the following commandContent-Type:application/x-www-form-urlencodedBut by default, it usesContent-Type:application/json.

Note: You can configure it to useapplication/x-www-form-urlencoded, Viewhttps://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

This means that to access the parameters, I need to usejson.Decoder.

Here is some sample code that can solve the problem:

type myData struct {
	Owner string
	Name  string
}

func handleAddNewRepo(w http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body)

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#a6e22e">myData</span>
<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">decoder</span>.<span style="color:#a6e22e">Decode</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">data</span>)
<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
	panic(<span style="color:#a6e22e">err</span>)
}

<span style="color:#a6e22e">owner</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">Owner</span>
<span style="color:#a6e22e">name</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">data</span>.<span style="color:#a6e22e">Name</span>
<span style="color:#75715e">//...

}


More tutorials: