How to print the bytes while the file is being downloaded ? -golang

后端 未结 4 1979
无人共我
无人共我 2021-01-31 06:29

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\")
    d         


        
4条回答
  •  日久生厌
    2021-01-31 07:08

    The stdlib now provides something like jimt's PassThru: io.TeeReader. It helps simplify things a bit:

    // 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{})
    
        // ...
    }
    

    playground

提交回复
热议问题