我想知道是否可以计算和打印下载文件时下载的字节数。out, err := os.Create("file.txt") defer out.Close() if err != nil { fmt.Println(fmt.Sprint(err) ) panic(err) } resp, err := http.Get("http://example.com/zip") defer resp.Body.Close() if err != nil { fmt.Println(fmt.Sprint(err) ) panic(err) } n, er := io.Copy(out, resp.Body) if er != nil { fmt.Println(fmt.Sprint(err) ) } fmt.Println(n, "bytes ")
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
stdlib 现在提供类似 jimt 的内容PassThru:io.TeeReader。它有助于简化一些事情:
// WriteCounter counts the number of bytes written to it.
type WriteCounter struct {
Total int64 // Total # of bytes transferred
}
// Write implements the io.Writer interface.
//
// Always completes and never returns an error.
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += int64(n)
fmt.Printf("Read %d bytes for a total of %d\n", n, wc.Total)
return n, nil
}
func main() {
// ...
// Wrap it with our custom io.Reader.
src = io.TeeReader(src, &WriteCounter{})
// ...
}
- 3 回答
- 0 关注
- 196 浏览
添加回答
举报
0/150
提交
取消