xml.NewDecoder(resp.Body).Decode给出EOF错误_GOLang

huangapple go评论97阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年7月22日 13:29:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/24879587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定