dpnvrt3119 2016-08-24 11:46
浏览 79
已采纳

使用golang http包获取帖子数据

I am new to golang, getting familiar with http package. I am having trouble in getting the post data I am sending using postman.

http://localhost:8084/dbTest is my URI. I am passing key: hub_id value: 1 using form-data. I tried following approaches,

req.ParseForm()
fmt.Println("hub_id", req.Form["hub_id"])
req.Form.Get("hub_id")

But none of the approach work. I am getting empty response.

Following is my code:

package main

import (
    "fmt"
    "net/http"
    "log"
) 

func dbtest(w http.ResponseWriter, req *http.Request) {
  req.ParseForm()
  fmt.Println("hub_id", req.Form["hub_id"])
  req.Form.Get("hub_id")
  fmt.Println(req.PostFormValue("hub_id")) //response is empty
}

func main() {

    http.HandleFunc("/dbTest", dbtest)

  log.Fatal(http.ListenAndServe(":8084", nil))
}

When I print req i get the following:

&{POST /dbTest HTTP/1.1 1 1 map[Origin:[chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop] Connection:[keep-alive] Content-Type:[multipart/form-data; boundary=----WebKitFormBoundarydFOTVjOJMeqOHnS3] Content-Length:[138] Accept-Language:[en-US,en;q=0.8] Cache-Control:[no-cache] Accept-Encoding:[gzip, deflate] Accept:[*/*] User-Agent:[Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36] Postman-Token:[ac7ae3a9-60f6-2146-3f1c-209de7622774]] 0xc210012e70 138 [] false localhost:8084 map[] map[] <nil> map[] 127.0.0.1:34152 /dbTest <nil>}

Solution: I found the solution. Since, content-type is mulipart/form-data I correct way to parse form is to use req.ParseMultipartForm http method.

  • 写回答

2条回答 默认 最新

  • doujiao3016 2016-08-24 13:01
    关注

    You are using incorrect Content-Type. When using Content-Type:application/x-www-form-urlencoded, r.ParseForm() will parse data correctly. Check r.Form afterwards.

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站