错误:读取Post请求的XML正文时出现EOF

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

error: EOF for reading XML body of Post request

问题

我在读取XML响应体时,在控制台上遇到了error: EOF错误。

以下是我的代码。

resp, err := http.Post(url, "application/xml", payload)
if err != nil {
	response.WriteErrorString(http.StatusInternalServerError, err.Error())
	return
}

defer resp.Body.Close()
dec := xml.NewDecoder(resp.Body)

if debug == true {
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println("=========== Response ==================")
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}
	fmt.Println(string(body))
	fmt.Println("=========== Response Ends =============")
}

err = dec.Decode(respStruct)

我怀疑ioutil.ReadAll没有按预期工作。

它为什么会抛出这个错误?

英文:

I'm getting error: EOF on console when I read the XML response body.

Below is my code.

resp, err := http.Post(url, "application/xml", payload)
if err != nil {
	response.WriteErrorString(http.StatusInternalServerError, err.Error())
	return
}

defer resp.Body.Close()
dec := xml.NewDecoder(resp.Body)

if debug == true {
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println("=========== Response ==================")
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}
	fmt.Println(string(body))
	fmt.Println("=========== Response Ends =============")
}

err = dec.Decode(respStruct)

I suspect ioutil.ReadAll is not working as expected.

Is there a reason why it's throwing this error?

答案1

得分: 3

xml.NewDecoder(resp.Body)可能已经读取了resp.Body的内容。因此出现了EOF消息。

你可以在“xml.NewDecoder(resp.Body).Decode Giving EOF Error”中看到相同的错误。

首先读取resp.Body,然后使用字符串与xml.Unmarshal一起使用可以避免重复读取和错误消息。

注意:一个类似的答案表明,最佳实践仍然是在从流中读取时使用xml.Decoder而不是xml.Unmarshal。所以确保不要两次读取resp.Body,它就会正常工作。

英文:

xml.NewDecoder(resp.Body) might already have read the content of resp.Body.
Hence the EOF message.

You can see the same error in "xml.NewDecoder(resp.Body).Decode Giving EOF Error"

Reading the resp.Body first, and using the string with xml.Unmarshal would avoid the double read and the error message.

Note: a similar answer shows that the best practice remains to use xml.Decoder instead of xml.Unmarshal when reading from streams.
So make sure you don't read resp.Body twice, and it will work.

huangapple
  • 本文由 发表于 2014年10月11日 22:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/26315668.html
匿名

发表评论

匿名网友

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

确定