小编典典

使用golang http包获取发布数据

go

我是golang的新手,熟悉http包。我在获取使用邮递员发送的邮政数据时遇到麻烦。

http://localhost:8084/dbTest是我的URI。我正在传递键:hub_id值:1使用表单数据。我尝试了以下方法

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

但是这些方法都不起作用。我得到的回应是空洞的。

以下是我的代码:

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))
}

当我打印要求时,我得到以下信息:

&{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>}

解决方案: 我找到了解决方案。既然,content-type是mulipart/form- data我解析表格的正确方法是使用req.ParseMultipartFormhttp方法。


阅读 376

收藏
2020-07-02

共1个答案

小编典典

您使用的不正确Content-Type。使用时Content-Type:application/x-www-form- urlencodedr.ParseForm()将正确解析数据。r.Form之后再检查。

2020-07-02