dqayok7935 2015-10-16 07:14
浏览 527
已采纳

golang解析POST请求

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?

  • 写回答

2条回答 默认 最新

  • douyan6958 2015-10-16 09:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理