xml.NewDecoder(resp.Body).Decode Giving EOF Error _GOLang

匿名 (未验证) 提交于 2019-12-03 02:28:01

问题:

I'm trying to Decode XML from body a html response.

=>I saved this response body as string to a Variable and successfully decoded Using xml.Unmarshal Function .Code for that :

    err = xml.Unmarshal([]byte(outs), &v)        if err != nil {     fmt.Printf("error is here: %v", err)     return                        } 

So I think problem is NOT with actual Content of Response body.

Now My Actual Code :

req1, err := http.NewRequest("GET", concat([]string{domain, defects_link}), nil) error_handler(err) req1.Close = true //I tried with and without this line   resp1, err := client.Do(req1) error_handler(err)  fmt.Printf("\n %s \n", resp1.Status)  defer resp1.Body.Close()//I tried with and without this line conts1, err := ioutil.ReadAll(resp1.Body) error_handler(err) fmt.Println("Response Body is Here :", string(conts1))//Contents are Printed Here 

Response is printed in last line of above code.But below code is giving "Error :EOF"

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

What is wrong in my code.Kindly Help

回答1:

If you already read the Body io.ReadCloser once (with conts1, err := ioutil.ReadAll(resp1.Body)), you cannot ask another function to read it again (or you will get the EOF error message).

I saved this response body as string to a Variable and successfully decoded Using xml.Unmarshal Function.

That seems the easiest approach to use the body content multiple times.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!