example_test upd
Vladimir Bauer
6 years ago
| 0 | 0 | package mpb_test |
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | crand "crypto/rand" | |
| 3 | 4 | "io" |
| 4 | 5 | "io/ioutil" |
| 5 | 6 | "math/rand" |
| 6 | "net/http" | |
| 7 | 7 | "time" |
| 8 | 8 | |
| 9 | 9 | "github.com/vbauerster/mpb/v4" |
| 32 | 32 | mpb.AppendDecorators(decor.Percentage()), |
| 33 | 33 | ) |
| 34 | 34 | // simulating some work |
| 35 | rng := rand.New(rand.NewSource(time.Now().UnixNano())) | |
| 35 | 36 | max := 100 * time.Millisecond |
| 36 | 37 | for i := 0; i < total; i++ { |
| 37 | 38 | start := time.Now() |
| 38 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 39 | time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) | |
| 39 | 40 | // since ewma decorator is used, we need to pass time.Since(start) |
| 40 | 41 | bar.Increment(time.Since(start)) |
| 41 | 42 | } |
| 47 | 48 | p := mpb.New() |
| 48 | 49 | bar := p.AddBar(100) |
| 49 | 50 | |
| 51 | rng := rand.New(rand.NewSource(time.Now().UnixNano())) | |
| 50 | 52 | max := 100 * time.Millisecond |
| 51 | 53 | for !bar.Completed() { |
| 52 | time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) | |
| 54 | time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) | |
| 53 | 55 | bar.Increment() |
| 54 | 56 | } |
| 55 | 57 | |
| 57 | 59 | } |
| 58 | 60 | |
| 59 | 61 | func ExampleBar_ProxyReader() { |
| 62 | var total int64 = 1024 * 1024 * 500 | |
| 63 | // crand is "crypto/rand" | |
| 64 | reader := io.LimitReader(crand.Reader, total) | |
| 65 | ||
| 60 | 66 | p := mpb.New() |
| 61 | // make http get request, ignoring errors | |
| 62 | resp, _ := http.Get("https://homebrew.bintray.com/bottles/libtiff-4.0.7.sierra.bottle.tar.gz") | |
| 63 | defer resp.Body.Close() | |
| 64 | ||
| 65 | // Assuming ContentLength > 0 | |
| 66 | bar := p.AddBar(resp.ContentLength, | |
| 67 | bar := p.AddBar(total, | |
| 67 | 68 | mpb.AppendDecorators( |
| 68 | decor.CountersKibiByte("%6.1f / %6.1f"), | |
| 69 | decor.CountersKibiByte("% .2f / % .2f"), | |
| 69 | 70 | ), |
| 70 | 71 | ) |
| 71 | 72 | |
| 72 | 73 | // create proxy reader |
| 73 | reader := bar.ProxyReader(resp.Body) | |
| 74 | proxyReader := bar.ProxyReader(reader) | |
| 75 | defer proxyReader.Close() | |
| 74 | 76 | |
| 75 | 77 | // and copy from reader, ignoring errors |
| 76 | io.Copy(ioutil.Discard, reader) | |
| 78 | io.Copy(ioutil.Discard, proxyReader) | |
| 77 | 79 | |
| 78 | 80 | p.Wait() |
| 79 | 81 | } |