fetcher.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package fetcher
  2. import (
  3. "git.bvbej.com/bvbej/base-golang/pkg/downloader/base"
  4. "git.bvbej.com/bvbej/base-golang/pkg/downloader/controller"
  5. )
  6. // Fetcher 对应协议的下载支持
  7. type Fetcher interface {
  8. // Setup 设置文件相关信息
  9. Setup(ctl controller.Controller)
  10. // Resolve 解析请求
  11. Resolve(req *base.Request) (res *base.Resource, err error)
  12. // Create 创建任务
  13. Create(res *base.Resource, opts *base.Options) (err error)
  14. // Start 开始
  15. Start() (err error)
  16. // Pause 暂停
  17. Pause() (err error)
  18. // Continue 继续
  19. Continue() (err error)
  20. // Progress 获取任务各个文件下载进度
  21. Progress() Progress
  22. // Wait 该方法会一直阻塞,直到任务下载结束
  23. Wait() (err error)
  24. }
  25. type DefaultFetcher struct {
  26. Ctl controller.Controller
  27. DoneCh chan error
  28. }
  29. func (f *DefaultFetcher) Setup(ctl controller.Controller) {
  30. f.Ctl = ctl
  31. f.DoneCh = make(chan error, 1)
  32. }
  33. func (f *DefaultFetcher) Wait() (err error) {
  34. return <-f.DoneCh
  35. }
  36. // Progress 获取任务中各个文件的已下载字节数
  37. type Progress []int64
  38. // TotalDownloaded 获取任务总下载字节数
  39. func (p Progress) TotalDownloaded() int64 {
  40. total := int64(0)
  41. for _, d := range p {
  42. total += d
  43. }
  44. return total
  45. }