英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论