vendor/github.com/ysmood/fetchup/fetchup.go
107 lines · 2025 bytes
1package fetchup
2
3import (
4 "context"
5 "fmt"
6 "io"
7 "log"
8 "net/http"
9 "os"
10 "sync"
11 "time"
12)
13
14type Fetchup struct {
15 Ctx context.Context
16
17 // To is the path to save the file.
18 To string
19
20 // URLs is the list of candidates, the fastest one will be used to download the file.
21 URLs []string
22
23 Logger Logger
24
25 // SpeedPacketSize is the size of the packet used to calculate the download speed.
26 // The size should be much smaller than the whole file size to download.
27 SpeedPacketSize int
28
29 MinReportSpan time.Duration
30
31 HttpClient *http.Client
32}
33
34func New(to string, us ...string) *Fetchup {
35 return &Fetchup{
36 Ctx: context.Background(),
37 To: to,
38 URLs: us,
39 Logger: log.New(os.Stderr, "", log.LstdFlags),
40 SpeedPacketSize: 64 * 1024,
41 MinReportSpan: time.Second,
42 HttpClient: &http.Client{
43 Transport: &DefaultTransport{UA: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"},
44 },
45 }
46}
47
48func (fu *Fetchup) Fetch() error {
49 u := fu.FastestURL()
50 if u == "" {
51 return &ErrNoURLs{fu.URLs}
52 }
53
54 return fu.Download(u)
55}
56
57type ErrNoURLs struct {
58 URLs []string
59}
60
61func (e *ErrNoURLs) Error() string {
62 return fmt.Sprintf("Not able to find a valid URL to download %v", e.URLs)
63}
64
65func (fu *Fetchup) FastestURL() (fastest string) {
66 setURL := sync.Once{}
67 ctx, cancel := context.WithCancel(fu.Ctx)
68 defer cancel()
69
70 wg := sync.WaitGroup{}
71 for _, u := range fu.URLs {
72 u := u
73
74 wg.Add(1)
75
76 go func() {
77 defer wg.Done()
78
79 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
80 if err != nil {
81 return
82 }
83
84 res, err := fu.HttpClient.Do(req)
85 if err != nil {
86 return
87 }
88 defer func() { _ = res.Body.Close() }()
89
90 if res.StatusCode == http.StatusOK {
91 buf := make([]byte, fu.SpeedPacketSize)
92 _, err = io.ReadFull(res.Body, buf)
93 if err != nil {
94 return
95 }
96
97 setURL.Do(func() {
98 fastest = u
99 cancel()
100 })
101 }
102 }()
103 }
104 wg.Wait()
105
106 return
107}