1. 带进度条大文件下载

    1.1.2. 带进度条的大文件下载

    1. import (
    2. "fmt"
    3. "io"
    4. "net/http"
    5. "os"
    6. "strings"
    7. "github.com/dustin/go-humanize"
    8. )
    9. type WriteCounter struct {
    10. Total uint64
    11. }
    12. func (wc *WriteCounter) Write(p []byte) (int, error) {
    13. n := len(p)
    14. wc.PrintProgress()
    15. }
    16. func (wc WriteCounter) PrintProgress() {
    17. fmt.Printf("\r%s", strings.Repeat(" ", 35))
    18. fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
    19. }
    20. func main() {
    21. fmt.Println("Download Started")
    22. fileUrl := "http://topgoer.com/static/2/9.png"
    23. err := DownloadFile("9.png", fileUrl)
    24. if err != nil {
    25. panic(err)
    26. }
    27. fmt.Println("Download Finished")
    28. }
    29. if err != nil {
    30. return err
    31. }
    32. resp, err := http.Get(url)
    33. if err != nil {
    34. out.Close()
    35. return err
    36. }
    37. defer resp.Body.Close()
    38. counter := &WriteCounter{}
    39. if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {
    40. out.Close()
    41. return err
    42. }
    43. fmt.Print("\n")
    44. out.Close()
    45. if err = os.Rename(filepath+".tmp", filepath); err != nil {
    46. return err
    47. }
    48. }