http - 只下载文件的一部分
问题描述
我想使用 go 从 Internet 下载类似文本的文件的一部分。--max-filesize
我想从中下载的网站似乎--range
不尊重 curl 。此外,我读到 httpMaxBytesReader
仍然会下载整个文件,但只存储其中的一部分。
有没有办法只获取文件的第一个 kb 然后关闭连接?相当于在 chrome 上加载大页面时按“x”。我在想我可以运行一个将网站读取到文件的线程,然后在一两毫秒后终止该线程。这可能吗?
解决方案
One simple way to do it without much error handling (which would have to added could be):
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
const readLimit = 1024 // bytes
func main() {
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
fixedReader := io.LimitedReader{R: resp.Body, N: readLimit}
data, _ := ioutil.ReadAll(fixedReader)
resp.Body.Close()
fmt.Println(string(data))
}
推荐阅读
- c# - 在 ASP.Net (Visual Studio 2013) 中以结构格式解析 Json 数据
- bash - linux命令行单引号转义问题
- r - 传单 R 中具有不同形状和颜色的自定义标记
- android - Android 上带有图像的 FCM 通知
- jmeter - 在 Jmeter 中使用 JsonExtractor 值
- react-native - 怎么设置全屏
何时嵌入 youtube 网址? - java - React to console inputs (commands) - how to handle multiple options most efficient?
- mysql - The MySQL query return an empty set
- android - 我想在 firebase android 的帮助下上传图片和文本?
- php - 如何使用 PHP 检查 s3 客户端的响应?