douhuigan8063 2014-03-15 08:20
浏览 275
已采纳

下载文件时如何打印字节? -golang

I'm wondering if it's possible to count and print the number of bytes downloaded while the file is being downloaded.

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 ")
  • 写回答

4条回答 默认 最新

  • duanmao1975 2014-03-15 10:39
    关注

    If I understand you correctly, you wish to display the number of bytes read, while the data is transferring. Presumably to maintain some kind of a progress bar or something. In which case, you can use Go's compositional data structures to wrap the reader or writer in a custom io.Reader or io.Writer implementation.

    It simply forwards the respective Read or Write call to the underlying stream, while doing some additional work with the (int, error) values returned by them. Here is an example you can run on the Go playground.

    package main
    
    import (
        "bytes"
        "fmt"
        "io"
        "os"
        "strings"
    )
    
    // PassThru wraps an existing io.Reader.
    //
    // It simply forwards the Read() call, while displaying
    // the results from individual calls to it.
    type PassThru struct {
        io.Reader
        total int64 // Total # of bytes transferred
    }
    
    // Read 'overrides' the underlying io.Reader's Read method.
    // This is the one that will be called by io.Copy(). We simply
    // use it to keep track of byte counts and then forward the call.
    func (pt *PassThru) Read(p []byte) (int, error) {
        n, err := pt.Reader.Read(p)
        pt.total += int64(n)
    
        if err == nil {
            fmt.Println("Read", n, "bytes for a total of", pt.total)
        }
    
        return n, err
    }
    
    func main() {
        var src io.Reader    // Source file/url/etc
        var dst bytes.Buffer // Destination file/buffer/etc
    
        // Create some random input data.
        src = bytes.NewBufferString(strings.Repeat("Some random input data", 1000))
    
        // Wrap it with our custom io.Reader.
        src = &PassThru{Reader: src}
    
        count, err := io.Copy(&dst, src)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
    
        fmt.Println("Transferred", count, "bytes")
    }
    

    The output it generates is this:

    Read 512 bytes for a total of 512
    Read 1024 bytes for a total of 1536
    Read 2048 bytes for a total of 3584
    Read 4096 bytes for a total of 7680
    Read 8192 bytes for a total of 15872
    Read 6128 bytes for a total of 22000
    Transferred 22000 bytes
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路