-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiget.go
117 lines (106 loc) · 2.32 KB
/
multiget.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"code.google.com/p/go.net/html"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"runtime"
"strings"
"sync"
)
// Commammand line flags definition
var link = flag.String("i", "", "Link to open")
var fileType = flag.String("e", "jpg,jpeg,gif,png", "Comma separated list of filetypes to fetch")
var debug = flag.Bool("d", false, "Enable debug")
var doGet = flag.Bool("g", false, "Download the links in current location")
var wg sync.WaitGroup
func GetAllLinks(data io.ReadCloser) (links []string, err error) {
tokenizer := html.NewTokenizer(data)
for {
tokenizer.Next()
token := tokenizer.Token()
switch token.Type {
case html.ErrorToken:
return
case html.EndTagToken:
case html.CommentToken:
case html.TextToken:
case html.StartTagToken, html.SelfClosingTagToken:
if *debug {
log.Print("type ", token.Type)
log.Print("data ", token.Data)
}
if token.Data == "a" {
for _, a := range token.Attr {
if a.Key == "href" {
for _, ext := range strings.Split(*fileType, ",") {
if strings.HasSuffix(a.Val, ext) {
if strings.HasPrefix(a.Val, "//") {
links = append(links, "http:"+a.Val)
} else {
links = append(links, a.Val)
}
}
}
}
}
}
}
}
return
}
func DownloadToLocal(l string) {
pieces := strings.Split(l, "/")
resp, err := http.Get(l)
if err != nil {
log.Print(err)
wg.Done()
return
}
defer resp.Body.Close()
out, err := os.Create(pieces[len(pieces)-1])
if err != nil {
log.Fatal(err)
}
defer out.Close()
io.Copy(out, resp.Body)
wg.Done()
}
func main() {
// must be here for flag parsing to work!
flag.Parse()
// parallelize this thing up
runtime.GOMAXPROCS(runtime.NumCPU())
if len(*link) == 0 {
log.Fatal("Please specify a link to fetch!")
}
if *debug {
log.Print("link:", *link)
log.Print("fileType:", *fileType)
log.Print("debug:", *debug)
log.Print("doGet:", *doGet)
log.Print("remaining args:", flag.Args())
}
resp, err := http.Get(*link)
if err != nil {
log.Fatal(fmt.Sprintf("Error fetching %s: %s", *link, err))
}
linkList, err := GetAllLinks(resp.Body)
if err != nil {
log.Fatal(err)
}
if !*doGet {
for _, l := range linkList {
log.Print("Link: ", l)
}
} else {
for _, l := range linkList {
wg.Add(1)
go DownloadToLocal(l)
}
}
wg.Wait()
}