首页 > 解决方案 > 只下载文件的一部分

问题描述

我想使用 go 从 Internet 下载类似文本的文件的一部分。--max-filesize我想从中下载的网站似乎--range不尊重 curl 。此外,我读到 httpMaxBytesReader仍然会下载整个文件,但只存储其中的一部分。

有没有办法只获取文件的第一个 kb 然后关闭连接?相当于在 chrome 上加载大页面时按“x”。我在想我可以运行一个将网站读取到文件的线程,然后在一两毫秒后终止该线程。这可能吗?

标签: httpgocurl

解决方案


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))
}

推荐阅读