Golang parse post request

I have an HTTP POST request with a payload

indices=0%2C1%2C2

Here is my holang 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 isn’t the POST request parsed using r.ParseForm(), while manaully parsing it using the url.ParseQuery(string(body))correct result?

+4
source share
2 answers

The problem is not the server code, this is normal, but just for your client, whatever it is, the correct header Content-Typefor the POST forms is missing . Just set the title to

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

In your client.

+12
source

Get the value form so that your parameters 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
+2
source

Source: https://habr.com/ru/post/1611889/


All Articles