Home >Backend Development >Golang >Why am I getting an EOF error when decoding XML from an HTTP response body in Go?
xml.NewDecoder(resp.Body).Decode Giving EOF Error in Go
When trying to decode XML from the HTTP response body using xml.NewDecoder, you may encounter an "EOF" error. This usually occurs when you have previously consumed the response body, making it unavailable for subsequent attempts to decode the XML.
Here's a breakdown of your code:
<code class="go">conts1, err := ioutil.ReadAll(resp1.Body)</code>
This code reads the body using ioutil.ReadAll, effectively consuming the entire response.
<code class="go">if err := xml.NewDecoder(resp1.Body).Decode(&v); err != nil { fmt.Printf("error is : %v", err)</code>
After reading the body with ioutil.ReadAll, trying to decode XML from the same body (resp1.Body) will result in an EOF error because the content has already been consumed.
Solution:
To resolve this issue, store the response body into a variable before consuming it using ioutil.ReadAll. This allows you to decode the XML from the buffered response.
<code class="go">resp1Bytes, err := ioutil.ReadAll(resp1.Body)</code>
Then, use this buffered response for decoding:
<code class="go">if err := xml.NewDecoder(bytes.NewReader(resp1Bytes)).Decode(&v); err != nil { fmt.Printf("error is : %v", err) }</code>
The above is the detailed content of Why am I getting an EOF error when decoding XML from an HTTP response body in Go?. For more information, please follow other related articles on the PHP Chinese website!