Home > Blockchain >  golang hangs when using multipart/form-data
golang hangs when using multipart/form-data

Time:11-02

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?

CodePudding user response:

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 screenshot of telegram api docs

  • Related