-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.go
100 lines (80 loc) · 1.77 KB
/
fetch.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
package httpmirror
import (
"context"
"fmt"
"io"
"io/fs"
"net/http"
"time"
)
func httpHead(ctx context.Context, client *http.Client, p string) (fs.FileInfo, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodHead, p, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: http status %d", ErrNotOK, resp.StatusCode)
}
return &fileInfo{
name: p,
resp: resp,
}, nil
}
func httpGet(ctx context.Context, client *http.Client, p string) (io.ReadCloser, fs.FileInfo, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p, nil)
if err != nil {
return nil, nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, nil, fmt.Errorf("%w: http status %d", ErrNotOK, resp.StatusCode)
}
return resp.Body, &fileInfo{
name: p,
resp: resp,
}, nil
}
var ErrNotOK = fmt.Errorf("http status not ok")
var _ fs.FileInfo = (*fileInfo)(nil)
type fileInfo struct {
name string
resp *http.Response
}
func (f fileInfo) Name() string {
return f.name
}
func (f fileInfo) IsDir() bool {
return false
}
func (f fileInfo) Mode() fs.FileMode {
return 0
}
func (f fileInfo) Sys() any {
return f.resp
}
func (f fileInfo) Size() int64 {
return f.resp.ContentLength
}
func (f fileInfo) ModTime() time.Time {
lastModified := f.resp.Header.Get("Last-Modified")
if lastModified == "" {
return time.Time{}
}
t, err := time.Parse(http.TimeFormat, lastModified)
if err != nil {
return time.Time{}
}
return t
}
func (f fileInfo) String() string {
return fmt.Sprintf("%s %s %d", f.Name(), f.ModTime(), f.Size())
}