Home >Backend Development >Golang >Why does `xml.NewDecoder(resp.Body).Decode` return an \'EOF\' error after `ioutil.ReadAll(resp1.Body)` reads the response body?

Why does `xml.NewDecoder(resp.Body).Decode` return an \'EOF\' error after `ioutil.ReadAll(resp1.Body)` reads the response body?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 15:57:02754browse

Why does `xml.NewDecoder(resp.Body).Decode` return an

EOF Error in xml.NewDecoder(resp.Body).Decode

Question:

When attempting to decode XML from an HTTP response using xml.NewDecoder(resp.Body).Decode, the error "EOF" occurs despite the response body being successfully decoded with xml.Unmarshal.

Code:

<code class="go">req1, err := http.NewRequest("GET", concat([]string{domain, defects_link}), nil)
error_handler(err)
req1.Close = true 

resp1, err := client.Do(req1)
error_handler(err)

fmt.Printf("\n %s \n", resp1.Status)

defer resp1.Body.Close()
conts1, err := ioutil.ReadAll(resp1.Body)
error_handler(err)
fmt.Println("Response Body is Here :", string(conts1))//Contents are Printed Here

if err := xml.NewDecoder(resp1.Body).Decode(&v); err != nil {
    fmt.Printf("error is : %v", err)
    return
}</code>

Explanation:

The error "EOF" (End-of-File) occurs because the response body has already been consumed by ioutil.ReadAll(resp1.Body) in the previous lines. This function reads all the data from the body until EOF, leaving nothing for xml.NewDecoder to decode.

Solution:

To resolve the issue, the body content should be copied into a new io.Reader before decoding with xml.NewDecoder. This allows multiple readers to access the body's content.

One approach is to use bytes.NewReader to create a new reader from the body content:

<code class="go">bodyBuffer := bytes.NewReader(conts1)
decoder := xml.NewDecoder(bodyBuffer)
err := decoder.Decode(&v)
if err != nil {
    fmt.Printf("error is : %v", err)
}</code>

Alternatively, resp1.Body can be "rewound" to its initial state using resp1.Body.Seek(0, 0):

<code class="go">_, err = resp1.Body.Seek(0, 0)
if err != nil {
    fmt.Printf("error is : %v", err)
}

decoder := xml.NewDecoder(resp1.Body)
err = decoder.Decode(&v)
if err != nil {
    fmt.Printf("error is : %v", err)
}</code>

The above is the detailed content of Why does `xml.NewDecoder(resp.Body).Decode` return an \'EOF\' error after `ioutil.ReadAll(resp1.Body)` reads the response body?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn