英文:
golang hangs when using multipart/form-data
问题
我想向 Telegram 发送一个空的 POST 请求。
问题是,如果我只关闭一次 multipart,它会一直挂起:
func main() {
var requestBody bytes.Buffer
multiPartWriter := multipart.NewWriter(&requestBody)
multiPartWriter.Close() // 只关闭一次
req, _ := http.NewRequest("POST", "https://api.telegram.org/bot<telegram token>/getme", &requestBody)
req.Header.Set("Content-Type", multiPartWriter.FormDataContentType())
client := &http.Client{}
client.Do(req)
}
但是如果我关闭两次 multipart,它就可以正常工作。
有人可以解释为什么会这样吗?
英文:
I want to make an empty post request to telegram.
The problem is if i close multipart once, it hangs forever:
func main() {
var requestBody bytes.Buffer
multiPartWriter := multipart.NewWriter(&requestBody)
multiPartWriter.Close() // closing once
req, _ := http.NewRequest("POST", "https://api.telegram.org/bot<telegram token>/getme", &requestBody)
req.Header.Set("Content-Type", multiPartWriter.FormDataContentType())
client := &http.Client{}
client.Do(req)
}
But if i close the multipart twice it works.
Can anyone explain why this happens?
答案1
得分: 0
我刚刚查看了Telegram API。
我猜问题的根源是你使用了一个未初始化的缓冲区。
你不需要这个缓冲区,在请求中也不需要任何有效载荷。你可以将请求数据设置为nil。像这样:
func main() {
req, err := http.NewRequest("POST", "https://api.telegram.org/bot<token>/getme", nil)
if err != nil {
panic(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
println(string(result))
}
我还建议你查看这里的文档,这个文档可以让你交互式地尝试API,还可以为每个请求生成代码。
要生成Go代码示例,你可以点击右上角的按钮,选择Go。
英文:
I just checked the Telegram API.
I guess the general problem is, that you use a buffer that is not initialized.
You don't need the buffer, you don't need any payload in the request. You can just pass nil as request data. Like this:
func main() {
req, err := http.NewRequest("POST", "https://api.telegram.org/bot<token>/getme", nil)
if err != nil {
panic(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
println(string(result))
}
I also recommend, that you check out the docs here this documentation lets you interactively try out the API, it can also generate the code for each request.
In order to generate Go code examples, you can click on the button at the upper right corner and chose your Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论