英文:
xml.NewDecoder(resp.Body).Decode Giving EOF Error _GOLang
问题
我正在尝试解码来自HTML响应的XML。
=>我将这个响应体保存为字符串,并成功使用xml.Unmarshal函数进行解码。代码如下:
err = xml.Unmarshal([]byte(outs), &v)
if err != nil {
fmt.Printf("error is here: %v", err)
return
}
所以我认为问题不在于实际的响应体内容。
现在是我的实际代码:
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))//内容在这里打印出来
上面代码的最后一行打印出了响应。但是下面的代码却报错"Error: EOF"。
if err := xml.NewDecoder(resp1.Body).Decode(&v); err != nil {
fmt.Printf("error is : %v", err)
return
}
我的代码有什么问题?请帮忙解决。
英文:
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
得分: 8
如果你已经使用conts1, err := ioutil.ReadAll(resp1.Body)
读取了Body io.ReadCloser
一次,那么你不能再要求另一个函数再次读取它(否则你会得到EOF
错误消息)。
> 我将这个响应体保存为字符串,并成功使用xml.Unmarshal函数解码。
这似乎是多次使用响应体内容的最简单方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论