使用multipart/form-data时,Golang卡住了。

huangapple go评论75阅读模式
英文:

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(&amp;requestBody)
	multiPartWriter.Close()      // closing once
	req, _ := http.NewRequest(&quot;POST&quot;, &quot;https://api.telegram.org/bot&lt;telegram token&gt;/getme&quot;, &amp;requestBody)
	req.Header.Set(&quot;Content-Type&quot;, multiPartWriter.FormDataContentType())
	client := &amp;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。

使用multipart/form-data时,Golang卡住了。

英文:

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(&quot;POST&quot;, &quot;https://api.telegram.org/bot&lt;token&gt;/getme&quot;, nil)
	if err != nil {
		panic(err)
	}

	client := &amp;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.

使用multipart/form-data时,Golang卡住了。

huangapple
  • 本文由 发表于 2021年11月2日 18:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69808562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定