gitee.com/quant1x/gox@v1.21.2/progressbar/xget/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  	"os"
     8  	"strings"
     9  
    10  	pgbar "gitee.com/quant1x/gox/progressbar"
    11  )
    12  
    13  type Downloader struct {
    14  	io.Reader
    15  	bar *pgbar.Bar
    16  }
    17  
    18  func NewDownloader(resp *http.Response) *Downloader {
    19  	nb := pgbar.NewBar(0, "下载进度", int(resp.ContentLength))
    20  	if resp.ContentLength > 10*1024 {
    21  		nb.SetUnit("B", "kb", 1024*1024)
    22  	}
    23  
    24  	if resp.ContentLength > 10*1024*1024 {
    25  		nb.SetUnit("B", "MB", 1024*1024)
    26  	}
    27  	return &Downloader{
    28  		Reader: resp.Body,
    29  		bar:    nb,
    30  	}
    31  }
    32  
    33  func (d *Downloader) Read(p []byte) (n int, err error) {
    34  	n, err = d.Reader.Read(p)
    35  
    36  	d.bar.Add(n)
    37  
    38  	return n, err
    39  }
    40  
    41  func main() {
    42  	if len(os.Args) <= 1 {
    43  		fmt.Println("xget url <filename>")
    44  	}
    45  	url := os.Args[1]
    46  
    47  	us := strings.Split(url, "/")
    48  	filename := us[len(us)-1]
    49  
    50  	if len(os.Args) == 3 {
    51  		filename = os.Args[2]
    52  	}
    53  
    54  	resp, err := http.Get(url)
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  
    59  	defer resp.Body.Close()
    60  
    61  	file, err := os.Create(filename)
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  	downloader := NewDownloader(resp)
    66  
    67  	io.Copy(file, downloader)
    68  
    69  	file.Close()
    70  }