-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgur-downloader.go
86 lines (75 loc) · 1.41 KB
/
imgur-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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"golang.org/x/net/html"
)
func createFile(imageURL string, image string) {
resp, err := http.Get(imageURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
file, err := os.Create(image + ".jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
b, err := io.Copy(file, resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("File size: ", b)
}
func getVal(tag html.Token) {
// Finds that id value of the imgur links
for _, div := range tag.Attr {
if div.Key == "id" {
if len(div.Val) == 7 {
image := div.Val
encodeURL(image)
}
}
}
}
func encodeURL(image string) {
imageURL := "https://i.imgur.com/" + image + ".jpg"
createFile(imageURL, image)
}
func tokenizer(resp *http.Response) {
z := html.NewTokenizer(resp.Body)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
// Error Token is end of the document
return
case tt == html.StartTagToken:
tag := z.Token()
// Check to see if the tag has <div> if not move to the next line.
div := tag.Data == "div"
if !div {
continue
}
getVal(tag)
}
}
}
func main() {
// Create directory
currentTime := time.Now()
dir := os.Args[2] + currentTime.Format("01-02-2006")
os.Mkdir(dir, 0700)
os.Chdir(dir)
// Fetch URL
url := os.Args[1]
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
tokenizer(resp)
}