Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: EOF for reading XML body of Post request

Tags:

go

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?

like image 826
Passionate Engineer Avatar asked Oct 17 '25 00:10

Passionate Engineer


1 Answers

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.

like image 145
VonC Avatar answered Oct 19 '25 22:10

VonC