-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex1.10.go
59 lines (52 loc) · 1.32 KB
/
ex1.10.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
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
"strings"
)
func main() {
start := time.Now()
ch := make(chan string)
var filename string
filecount := make(map[string]int)
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url, "http://") {
filecount[url] += 1
filename = url + fmt.Sprintf(".%d", filecount[url]) + ".txt"
url = "http://" + url
} else {
url = url[7:]
filecount[url] += 1
filename = url + fmt.Sprintf(".%d", filecount[url]) + ".txt"
}
go fetch(url, ch, filename)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}
func fetch(url string, ch chan<- string, filename string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err)
return
}
savedFile,err := os.Create(filename)
if err != nil {
ch <- fmt.Sprint(err)
return
}
nbytes, err := io.Copy(savedFile, resp.Body)
resp.Body.Close()
if err != nil {
ch <- fmt.Sprintf("while reading %s: %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
}