io example without http
Vladimir Bauer
6 years ago
| 0 | 0 | package main |
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | "fmt" | |
| 3 | "crypto/rand" | |
| 4 | 4 | "io" |
| 5 | "net/http" | |
| 6 | "os" | |
| 7 | "path/filepath" | |
| 5 | "io/ioutil" | |
| 8 | 6 | "time" |
| 9 | 7 | |
| 10 | 8 | "github.com/vbauerster/mpb/v4" |
| 12 | 10 | ) |
| 13 | 11 | |
| 14 | 12 | func main() { |
| 15 | url := "https://github.com/onivim/oni/releases/download/v0.3.4/Oni-0.3.4-amd64-linux.deb" | |
| 16 | ||
| 17 | resp, err := http.Get(url) | |
| 18 | if err != nil { | |
| 19 | panic(err) | |
| 20 | } | |
| 21 | defer resp.Body.Close() | |
| 22 | ||
| 23 | if resp.StatusCode != http.StatusOK { | |
| 24 | fmt.Printf("Server return non-200 status: %s\n", resp.Status) | |
| 25 | return | |
| 26 | } | |
| 27 | ||
| 28 | size := resp.ContentLength | |
| 29 | ||
| 30 | // create dest | |
| 31 | destName := filepath.Base(url) | |
| 32 | dest, err := os.Create(destName) | |
| 33 | if err != nil { | |
| 34 | fmt.Printf("Can't create %s: %v\n", destName, err) | |
| 35 | return | |
| 36 | } | |
| 37 | defer dest.Close() | |
| 13 | var total int64 = 1024 * 1024 * 500 | |
| 14 | reader := io.LimitReader(rand.Reader, total) | |
| 38 | 15 | |
| 39 | 16 | p := mpb.New( |
| 40 | 17 | mpb.WithWidth(60), |
| 41 | 18 | mpb.WithRefreshRate(180*time.Millisecond), |
| 42 | 19 | ) |
| 43 | 20 | |
| 44 | bar := p.AddBar(size, mpb.BarStyle("[=>-|"), | |
| 21 | bar := p.AddBar(total, mpb.BarStyle("[=>-|"), | |
| 45 | 22 | mpb.PrependDecorators( |
| 46 | decor.CountersKibiByte("% 6.1f / % 6.1f"), | |
| 23 | decor.CountersKibiByte("% .2f / % .2f"), | |
| 47 | 24 | ), |
| 48 | 25 | mpb.AppendDecorators( |
| 49 | decor.EwmaETA(decor.ET_STYLE_MMSS, float64(size)/2048), | |
| 26 | decor.EwmaETA(decor.ET_STYLE_GO, float64(total)/2048), | |
| 50 | 27 | decor.Name(" ] "), |
| 51 | 28 | decor.AverageSpeed(decor.UnitKiB, "% .2f"), |
| 52 | 29 | ), |
| 53 | 30 | ) |
| 54 | 31 | |
| 55 | 32 | // create proxy reader |
| 56 | reader := bar.ProxyReader(resp.Body) | |
| 33 | proxyReader := bar.ProxyReader(reader) | |
| 34 | defer proxyReader.Close() | |
| 57 | 35 | |
| 58 | // and copy from reader, ignoring errors | |
| 59 | io.Copy(dest, reader) | |
| 36 | // copy from proxyReader, ignoring errors | |
| 37 | io.Copy(ioutil.Discard, proxyReader) | |
| 60 | 38 | |
| 61 | 39 | p.Wait() |
| 62 | 40 | } |