大文件下载
带有进度条的大文件下载,将响应主体传递到其中io.Copy(),使用TeeReader则可以传递计数器来跟踪进度。在下载时,将文件另存为临时文件,因此在完全下载文件之前,不会覆盖有效文件。
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/dustin/go-humanize"
)
type WriteCounter struct {
Total uint64
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.PrintProgress()
return n, nil
}
func (wc WriteCounter) PrintProgress() {
fmt.Printf("
%s", strings.Repeat(" ", 35))
fmt.Printf("
Downloading... %s complete", humanize.Bytes(wc.Total))
}
func main() {
fmt.Println("Download Started")
fileUrl := "http://xxx/static/1.png"
err := DownloadFile("1.png", fileUrl)
if err != nil {
panic(err)
}
fmt.Println("Download Finished")
}
func DownloadFile(filepath string, url string) error {
out, err := os.Create(filepath + ".tmp")
if err != nil {
return err
}
resp, err := http.Get(url)
if err != nil {
out.Close()
return err
}
defer resp.Body.Close()
counter := &WriteCounter{}
if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {
out.Close()
return err
}
fmt.Print("
")
out.Close()
if err = os.Rename(filepath+".tmp", filepath); err != nil {
return err
}
return nil
}