golang ioutil.ReadAll
时间: 2023-10-12 15:43:42 浏览: 213
在Golang中,`ioutil.ReadAll`函数用于从`io.Reader`接口中读取所有可用的数据,直到遇到EOF(文件结束符)为止,并将读取的数据以字节切片的形式返回。
以下是`ioutil.ReadAll`的基本用法示例:
```go
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 发送GET请求并获取响应
resp, err := http.Get("https://www.example.com")
if err != nil {
fmt.Println("发送请求失败:", err)
return
}
defer resp.Body.Close()
// 读取响应的全部内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败:", err)
return
}
// 打印响应的内容
fmt.Println(string(body))
}
```
在上面的示例中,我们使用`http.Get`发送了一个GET请求,并获取到了响应。然后,我们使用`ioutil.ReadAll`函数从响应的Body中读取所有的数据,并将其存储在`body`变量中。最后,我们使用`string`函数将字节切片转换为字符串,并打印出来。
需要注意的是,`ioutil.ReadAll`一次性读取整个数据流到内存中,适用于较小的数据量。对于大型数据流,可能需要使用逐块读取的方式以避免占用过多的内存。
阅读全文
相关推荐
















