-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.go
More file actions
76 lines (64 loc) · 1.71 KB
/
example.go
File metadata and controls
76 lines (64 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/hritikr/dlfetch"
)
func main() {
// Create a new fetcher with custom options
var downloadMonitor dlfetch.Monitor = dlfetch.NewMonitor()
fetcher := dlfetch.New(
dlfetch.WithMaxWorkers(4),
dlfetch.WithOnComplete(func(result dlfetch.DownloadResult) {
fmt.Printf(
"Download completed: id=%d file=%s path=%s mime=%s\n",
result.ID,
result.FileName,
result.Path,
result.MimeType,
)
}),
dlfetch.WithOnError(func(req dlfetch.DownloadRequest, err error) {
log.Printf(
"Download failed: id=%d url=%s error=%v\n",
req.ID,
req.URL,
err,
)
}),
dlfetch.WithMonitor(downloadMonitor),
)
// Start worker pool
fetcher.Start()
// Enqueue a single download
enqueueResult := fetcher.Enqueue(dlfetch.DownloadRequest{
ID: 1,
URL: "https://filesamples.com/samples/video/m4v/sample_3840x2160.m4v",
})
if enqueueResult.Error != nil {
log.Printf("Failed to enqueue download: %v", enqueueResult.Error)
fmt.Println("Nothing to download.")
return
}
log.Println("Download queued successfully, waiting for completion...")
// Check EventSignal to get updates on the download progress
for {
<-downloadMonitor.EventSignal()
snapshot := downloadMonitor.GetSnapshot()
data, err := json.MarshalIndent(snapshot, "", " ")
if err != nil {
log.Printf("Error marshaling snapshot: %v", err)
} else {
log.Printf("=> Snapshot:\n%s\n", string(data))
}
// Exit on download complete
if snapshot.Count.Completed+snapshot.Count.Failed == snapshot.Count.Total &&
snapshot.Count.Total > 0 {
break
}
}
fmt.Println("All downloads processed.")
// Stop the fetcher and wait for workers to exit
fetcher.Stop()
}