英文:
golang parse POST request
问题
我有一个带有负载的HTTP POST请求
indices=0%2C1%2C2
这是我的Golang后端代码
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"))
输出结果:
r.PostForm map[]
r.Form map[]
r.Body indices=0%2C1%2C2
indices from body 0,1,2
为什么POST请求没有被r.ParseForm()
解析,而手动使用url.ParseQuery(string(body))
解析可以得到正确的结果?
英文:
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?
答案1
得分: 18
问题不在于你的服务器代码,它是正确的,而是你的客户端缺少正确的Content-Type
头部信息用于POST表单。只需在你的客户端中设置头部信息为:
Content-Type: application/x-www-form-urlencoded
英文:
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.
答案2
得分: 8
从你的 http.Request
中使用 PostFormValue("params")
获取参数的值。
err := r.ParseForm()
if err != nil{
panic(err)
}
params := r.PostFormValue("params") // 使用键获取参数值
请注意,这是一个示例代码片段,用于从 HTTP 请求中获取名为 "params" 的参数值。你可以根据自己的需求进行修改和使用。
英文:
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论