-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_downloader.go
68 lines (56 loc) · 1.36 KB
/
image_downloader.go
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
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
type ImageDownloader struct {
HTTPClient HTTPClient
FileChecker FileChecker
}
func (d *ImageDownloader) DownloadImage(url, downloadDir string) error {
fileName := filepath.Base(url)
filePath := filepath.Join(downloadDir, fileName)
// Check if the file already exists
if d.FileChecker.IsFileExists(filePath) {
// File already exists, skip downloading
return nil
}
// Create the file
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file: %v", err)
}
defer file.Close()
// Download the image
resp, err := d.HTTPClient.Get(url)
if err != nil {
return fmt.Errorf("failed to download image: %v", err)
}
defer resp.Body.Close()
// Check if the response status is OK
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download image, status: %s", resp.Status)
}
// Copy the response body to the file
_, err = io.Copy(file, resp.Body)
if err != nil {
return fmt.Errorf("failed to save image: %v", err)
}
return nil
}
func batchImageURLs(imageURLs []string, batchSize int) [][]string {
var batches [][]string
length := len(imageURLs)
for i := 0; i < length; i += batchSize {
end := i + batchSize
if end > length {
end = length
}
batch := imageURLs[i:end]
batches = append(batches, batch)
}
return batches
}