13

I have a HTTP POST request with payload

indices=0%2C1%2C2

Here is my golang backend code

err := r.ParseForm()
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
log.Println("r.PostForm", r.PostForm)
log.Println("r.Form", r.Form)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
log.Println("r.Body", string(body))

values, err := url.ParseQuery(string(body))
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
log.Println("indices from body", values.Get("indices"))

Output:

r.PostForm map[]
r.Form map[]
r.Body indices=0%2C1%2C2
indices from body 0,1,2

Why is it that the POST request is not parsed by r.ParseForm(), while manaully parsing it with url.ParseQuery(string(body)) gives the correct result?

paradite
  • 6,238
  • 3
  • 40
  • 58

2 Answers2

18

The problem is not in your server code which is fine, but simply that your client, whatever it is, is missing the correct Content-Type header for POST forms. Simply set the header to

Content-Type: application/x-www-form-urlencoded

In your client.

Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • Same thing when you're working with XML / JSON. If your request is sending json always set the header ``Content-Type: application/json``. Same for XML. Its a very good practice, (and sometimes mandatory), to configure the request according to its content to avoid backends the need to "guess" what's processing. – Federico Leon Apr 27 '17 at 20:14
8

Get value form your params use PostFormValue("params") from your http.Request

err := r.ParseForm() 
if err != nil{
       panic(err)
}

params := r.PostFormValue("params") // to get params value with key
yaziedda
  • 111
  • 1
  • 7