-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpfs.go
51 lines (42 loc) · 890 Bytes
/
httpfs.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
package httpfs
import (
"errors"
"io/fs"
"net/http"
"net/url"
)
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type httpFS struct {
httpClient httpClient
baseURL *url.URL
}
var _ fs.FS = (*httpFS)(nil) // Ensure HTTPFS implements FS.
func New(httpClient httpClient, baseURL *url.URL) *httpFS {
return &httpFS{
httpClient: httpClient,
baseURL: baseURL,
}
}
func (f *httpFS) Open(name string) (fs.File, error) {
req := &http.Request{
Method: "GET",
URL: f.baseURL.ResolveReference(&url.URL{Path: name}),
}
resp, err := f.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
_ = resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, fs.ErrNotExist
}
return nil, errors.New("HTTP error: " + resp.Status)
}
return &httpFile{
req: req,
resp: resp,
}, nil
}