我应该复制resp.Body吗?

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

Do I copy resp.Body?

问题

我正在学习Go语言,并且我有以下的代码,它可以正常工作:

resp, err := http.Get(url)  // 获取HTML
   ...
doc, err := html.Parse(resp.Body)  // 解析HTML页面

现在我想先打印出HTML,然后再进行解析:

resp, err := http.Get(url)
   ...
b, err := ioutil.ReadAll(resp.Body)  // 添加了这一行,但现在无法工作...
doc, err := html.Parse(resp.Body)

我猜测问题的原因是resp.Body是一个读取器,我不能调用两次读取操作?有什么办法可以正确地实现这个需求吗?复制resp.Body?

英文:

I am learning go and I have the following code which works fine:

resp, err := http.Get(url)  // get the html
   ...
doc, err := html.Parse(resp.Body)  // parse the html page

Now I want to print out the html first then do the parsing:

resp, err := http.Get(url)
   ...
b, err := ioutil.ReadAll(resp.Body)  // this line is added, not working now...
doc, err := html.Parse(resp.Body)

I guess the reason is resp.Body is a reader, I can not call the read twice? Any idea how can I do this correctly? Copy the resp.Body?

答案1

得分: 5

因为客户端从网络流式传输响应主体,所以不可能读取两次主体。

像你已经做的那样,将响应读取为[]byte。使用bytes.NewReader在字节上为HTML解析器创建一个io.Reader

resp, err := http.Get(url)
...
b, err := io.ReadAll(resp.Body)
doc, err := html.Parse(bytes.NewReader(b))
英文:

Because the client streams the response body from the network, it's not possible to read the body twice.

Read the response to a []byte as you are already doing. Create a io.Reader on the bytes for the HTML parser using bytes.NewReader.

resp, err := http.Get(url)
...
b, err := io.ReadAll(resp.Body)  
doc, err := html.Parse(bytes.NewReader(b))

huangapple
  • 本文由 发表于 2016年1月21日 13:14:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/34915873.html
匿名

发表评论

匿名网友

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

确定