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

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

Copy a html.Response, then get the string

问题

我已经创建了一个名为Url的类型,它应该包含响应体。

type Url struct {
    Address string
    Refresh string
    Watch   string
    Found   bool
    Body    bytes.Buffer // bytes.Buffer不需要初始化
}

使用正确的Address创建了一个Url对象,然后我执行了以下操作:

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

现在我想做类似下面的操作,但我无法摆脱它:

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

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

之后,我想从该缓冲区/写入器/任何其他地方获取字符串,但我认为一旦我解决了前面的复制问题,这将很容易。

祝好,
Le Barde。

英文:

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.

答案1

得分: 1

我猜你想使用ioutil.ReadAll函数,它返回[]byte类型:

resp, err := http.Get(url.Address)
if err != nil {
   // 处理错误
}
defer resp.Body.Close()
url.Body, err = ioutil.ReadAll(resp.Body)
英文:

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)

huangapple
  • 本文由 发表于 2016年11月20日 16:14:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/40701992.html
匿名

发表评论

匿名网友

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

确定