我在使用 http 包发送简单的 POST 请求时遇到了一些问题:
var http_client http.Client
req, err := http.NewRequest("POST", "http://login.blah", nil)
if err != nil {
return errors.New("Error creating login request: " + err.Error())
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
body := fmt.Sprintf("?username=%s&password=%s&version=%d", client.Username, client.Password, launcherVersion)
fmt.Println("Body:", body)
req.Body = ioutil.NopCloser(bytes.NewBufferString(body))
req.ParseForm()
resp, err := http_client.Do(req)
if err != nil {
return errors.New("Error sending login request: " + err.Error())
}
我从印刷品中看到了正确的主体:
Body: ?username=test&password=test&version=13
但 60 秒后,我得到:
Error sending login request: unexpected EOF
我确信这与我如何设置请求正文有关,因为使用 Wireshark 观看它会向我显示请求,该请求立即发出,Content-Length
没有正文的值为 0。
POST / HTTP/1.1
Host: login.blah
User-Agent: Go http package
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip