You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.1 KiB

  1. package progressbar
  2. import "fmt"
  3. // the progressbar indicates the current status and progress would be desired.
  4. // ref: https://www.pixelstech.net/article/1596946473-A-simple-example-on-implementing-progress-bar-in-GoLang
  5. type Bar struct {
  6. percent int64 // progress percentage
  7. cur int64 // current progress
  8. start int64 // the init starting value for progress
  9. total int64 // total value for progress
  10. rate string // the actual progress bar to be printed
  11. graph string // the fill value for progress bar
  12. }
  13. func (bar *Bar) NewOption(start, total int64) {
  14. bar.cur = start
  15. bar.start = start
  16. bar.total = total
  17. bar.graph = "█"
  18. bar.percent = bar.getPercent()
  19. }
  20. func (bar *Bar) getPercent() int64 {
  21. return int64(float32(bar.cur-bar.start) / float32(bar.total-bar.start) * 100)
  22. }
  23. func (bar *Bar) Play(cur int64) {
  24. bar.cur = cur
  25. last := bar.percent
  26. bar.percent = bar.getPercent()
  27. if bar.percent != last && bar.percent%2 == 0 {
  28. bar.rate += bar.graph
  29. }
  30. fmt.Printf("\r[%-50s]%3d%% %8d/%d", bar.rate, bar.percent, bar.cur, bar.total)
  31. }
  32. func (bar *Bar) Finish() {
  33. fmt.Println()
  34. }