使用golang http包获取post数据
时间:2023-03-07
浏览:389
作者:佚名
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《使用golang http包获取post数据》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到golang等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!
问题内容
我是 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))
}
当我打印 req 时,我得到以下信息:
&{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[] map[] 127.0.0.1:34152 /dbTest }
解决方案: 我找到了解决方案。因为,内容类型是mulipart/form- data我解析表单的正确方法是使用req.ParseMultipartFormhttp 方法。
正确答案
您使用的是不正确的Content-Type. 使用时Content-Type:application/x-www-form- urlencoded,r.ParseForm()将正确解析数据。r.Form事后检查。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
