Codebase list golang-github-vbauerster-mpb / 53fa35f
io example without http Vladimir Bauer 6 years ago
1 changed file(s) with 11 addition(s) and 33 deletion(s). Raw diff Collapse all Expand all
00 package main
11
22 import (
3 "fmt"
3 "crypto/rand"
44 "io"
5 "net/http"
6 "os"
7 "path/filepath"
5 "io/ioutil"
86 "time"
97
108 "github.com/vbauerster/mpb/v4"
1210 )
1311
1412 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)
3815
3916 p := mpb.New(
4017 mpb.WithWidth(60),
4118 mpb.WithRefreshRate(180*time.Millisecond),
4219 )
4320
44 bar := p.AddBar(size, mpb.BarStyle("[=>-|"),
21 bar := p.AddBar(total, mpb.BarStyle("[=>-|"),
4522 mpb.PrependDecorators(
46 decor.CountersKibiByte("% 6.1f / % 6.1f"),
23 decor.CountersKibiByte("% .2f / % .2f"),
4724 ),
4825 mpb.AppendDecorators(
49 decor.EwmaETA(decor.ET_STYLE_MMSS, float64(size)/2048),
26 decor.EwmaETA(decor.ET_STYLE_GO, float64(total)/2048),
5027 decor.Name(" ] "),
5128 decor.AverageSpeed(decor.UnitKiB, "% .2f"),
5229 ),
5330 )
5431
5532 // create proxy reader
56 reader := bar.ProxyReader(resp.Body)
33 proxyReader := bar.ProxyReader(reader)
34 defer proxyReader.Close()
5735
58 // and copy from reader, ignoring errors
59 io.Copy(dest, reader)
36 // copy from proxyReader, ignoring errors
37 io.Copy(ioutil.Discard, proxyReader)
6038
6139 p.Wait()
6240 }