progress.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package multicloud
  15. import (
  16. "io"
  17. "time"
  18. )
  19. func NewProgress(totalSize int64, maxPercent int, reader io.Reader, callback func(progress float32)) io.Reader {
  20. body := &sProgress{
  21. total: totalSize,
  22. maxPercent: maxPercent,
  23. callback: callback,
  24. }
  25. return io.TeeReader(reader, body)
  26. }
  27. type sProgress struct {
  28. refreshSeconds int
  29. count int64
  30. total int64
  31. start time.Time
  32. callback func(progress float32)
  33. maxPercent int
  34. }
  35. func (r *sProgress) Write(p []byte) (int, error) {
  36. if r.start.IsZero() {
  37. r.start = time.Now()
  38. }
  39. n := len(p)
  40. r.count += int64(n)
  41. if r.callback != nil && r.total > 0 && time.Now().Sub(r.start) > time.Second*1 {
  42. r.callback(float32(float64(r.count) / float64(r.total) * float64(r.maxPercent)))
  43. r.start = time.Now()
  44. }
  45. return n, nil
  46. }