在GOlang中仅下载文件的一部分

I want to download just part of a text-like file from the internet using go. It appears that curl --max-filesize and --range aren't respected by the websites I want to download from. Additionally, I read that the http MaxBytesReader still downloads the entire file, but only stores part of it.

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

谢谢

评论
你无可取代
你无可取代

一种无需太多错误处理(可能必须添加)的简化方法:

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))
}
点赞
评论