duanpu1963 2018-11-16 06:43
浏览 28
已采纳

http请求后如何获得响应

I'm studying Go and am a real newbie in this field.

I am facing a problem when I try to copy some value.

What I am doing is:

  1. I want to get some response in [response] using httpRequest.
httpClient := &http.Client{}
response, err := httpClient.Do(req)
if err != nil {
   panic(err)
}
  1. After that, I want to save the stored value in response at 'origin.txt'
origin_ ,_:= ioutil.ReadAll(response.Body)
f_, err := os.Create("origin.txt")
f_.Write(origin_);
  1. And I want to get a specific value by using goquery package.
doc, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
    log.Fatal(err)
}
doc.Find(".className").Each(func(i int, s *goquery.Selection) {
    w.WriteString("============" + strconv.Itoa(i) + "============")
    s.Find("tr").Each(func(i int, s_ *goquery.Selection) {
    fmt.Println(s_.Text())
    w.WriteString(s_.Text())    
    })
}

)

But in this case, I can get a value exactly what I want from 2) but cannot get anything from 3).

At first, I think the problem is, the response object at 3) is affected by 2) action. Because it is a reference object.

So I tried to copy it to another object and then do it again.

origin := *response

but, I got the same result as first.

What should I do? How can I assign a reference value to another one by its value?

Should I request it twice for each attempt?

  • 写回答

1条回答 默认 最新

  • dqm4977 2018-11-16 06:51
    关注

    I actually don't see where you use shared resources between 2 and 3.

    However that being said origin := *response won't buy you much. The data (response.Body) is a io.ReadCloser. The ioutil.ReadAll() will consume and store all the data that the stream has. You only get to do this once.

    However you have the data stored in origin. If you need another io.Reader for that data (say for case 3), then you can make that byte slice look like an io.Reader again: bytes.NewReader(origin).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格