英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论