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