donglu4633
2016-11-20 08:14
浏览 129
已采纳

复制一个html.Response,然后获取字符串

I have made an Url type that should contain the response body.

type Url struct {
    Address string
    Refresh string
    Watch   string
    Found   bool
    Body    bytes.Buffer // bytes.Buffer needs no initialization
}

An Url object is created with the right Address, and then I do

resp, err := http.Get(url.Address)

Now I would like to do something like the following, but I cannot get out of it:

io.Copy(url.Body, b) // Copy that to the Url buffer

As for now, the Url.Body field can be modified to another type if needed.

Afterwards, I want to get the string from that Buffer/Writer/whatever, but I assume this will be easy as soon as I will manage the former copy.

Regards, Le Barde.

图片转代码服务由CSDN问答提供 功能建议

我已经创建了一个应包含响应正文的 Url 类型。

  type Url结构{
地址字符串
刷新字符串
监视字符串
找到的布尔值
主体字节。缓冲区//字节。缓冲区不需要初始化
} 
 <  / code>  
 
 

使用正确的 Address 创建一个Url对象,然后执行

  resp  ,err:= http.Get(url.Address)
   
 
 

现在,我想执行以下操作,但是我无法摆脱困境:

  io.Copy(url.Body,b)//将其复制到Url缓冲区
   
 
 

目前 , Url.Body 字段可以根据需要修改为另一种类型。

此后,我想从该Buffer / Writer /任何东西中获取字符串,但是 我认为,一旦我要管理以前的副本,这将很容易。

致谢, Le Barde。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drq22639 2016-11-20 08:27
    已采纳

    I guess you want to use ioutil.ReadAll which returns []byte:

    resp, err := http.Get(url.Address)
    if err != nil {
       // handle error
    }
    defer resp.Body.Close()
    url.Body, err = ioutil.ReadAll(resp.Body)
    
    打赏 评论

相关推荐 更多相似问题