-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep01.go
91 lines (75 loc) · 1.43 KB
/
step01.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
// Step01: 逐次ダウンロード
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
var baseURL *url.URL
func init() {
const baseURLStr = "http://localhost:8080/html/step01.html"
_url, err := url.Parse(baseURLStr)
if err != nil {
panic(err)
}
baseURL = _url
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
srcs, err := fetchHTML(baseURL)
if err != nil {
return err
}
for _, src := range srcs {
fmt.Println("download", src)
if err := download("imgs", src); err != nil {
return err
}
}
return nil
}
func download(dir, dlurlStr string) error {
dlurl := *baseURL
if strings.HasPrefix(dlurlStr, "/") {
path, query, ok := strings.Cut(dlurlStr, "?")
dlurl.Path = path
if ok {
dlurl.RawQuery = query
}
} else {
dlurl = *dlurl.JoinPath(dlurlStr)
}
req, err := http.NewRequest(http.MethodGet, dlurl.String(), nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("invalid status %d", resp.StatusCode)
}
defer resp.Body.Close()
_, filename := path.Split(dlurl.Path)
dlpath := filepath.Join(dir, filename)
file, err := os.Create(dlpath)
if err != nil {
return err
}
defer file.Close()
if _, err := io.Copy(file, resp.Body); err != nil {
return err
}
return nil
}