首页 > 解决方案 > 从邮递员获取http post请求中的参数

问题描述

我有一个 Go 服务器,但似乎无法从 POST 请求中获取服务器中的 POST(表单)参数列表

当我在 Body 选项卡中选择的选项是form-data并且请求如下所示时,我从邮递员发送请求:

POST /todo/323/item HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: ef4b5606-3079-fb02-824f-f58ae89ee6f3
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="aaa"

skhdfb
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="test"

1213
------WebKitFormBoundary7MA4YWxkTrZu0gW--

I get null but when the option is x-www-form-urlencodedit works fine. 我该怎么办?

这就是我尝试获取价值的方式:

fmt.Fprintln(w, req.FormValue("aaa"))

在此先感谢您的帮助

标签: gohttprequest

解决方案


当它是多部分时,您要么必须这样做:

req.ParseMultipartForm(0)
fmt.Println(req.FormValue("aaa"))

或者如果您不想将整个内容加载到内存中,您可以这样做:

form, err := req.MultipartReader()
for {
    part, err := form.NextPart()
    if err == io.EOF {
        break
    }
    if part.FormName() == "aaa" {
        buf := new(bytes.Buffer)
        buf.ReadFrom(part)
        fmt.Println(buf.String())
    } 
}

推荐阅读