forked from TRON-US/go-btfs-files
-
Notifications
You must be signed in to change notification settings - Fork 7
/
webfile.go
89 lines (77 loc) · 1.86 KB
/
webfile.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
package files
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
)
// WebFile is an implementation of File which reads it
// from a Web URL (http). A GET request will be performed
// against the source when calling Read().
type WebFile struct {
body io.ReadCloser
url *url.URL
contentLength int64
}
// NewWebFile creates a WebFile with the given URL, which
// will be used to perform the GET request on Read().
func NewWebFile(url *url.URL) *WebFile {
return &WebFile{
url: url,
}
}
func (wf *WebFile) start() error {
if wf.body == nil {
s := wf.url.String()
resp, err := http.Get(s)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("got non-2XX status code %d: %s", resp.StatusCode, s)
}
wf.body = resp.Body
wf.contentLength = resp.ContentLength
}
return nil
}
// Read reads the File from it's web location. On the first
// call to Read, a GET request will be performed against the
// WebFile's URL, using Go's default HTTP client. Any further
// reads will keep reading from the HTTP Request body.
func (wf *WebFile) Read(b []byte) (int, error) {
if err := wf.start(); err != nil {
return 0, err
}
return wf.body.Read(b)
}
// Close closes the WebFile (or the request body).
func (wf *WebFile) Close() error {
if wf.body == nil {
return nil
}
return wf.body.Close()
}
// TODO: implement
func (wf *WebFile) Seek(offset int64, whence int) (int64, error) {
return 0, ErrNotSupported
}
func (wf *WebFile) Size() (int64, error) {
if err := wf.start(); err != nil {
return 0, err
}
if wf.contentLength < 0 {
return -1, errors.New("Content-Length hearer was not set")
}
return wf.contentLength, nil
}
func (wf *WebFile) AbsPath() string {
return wf.url.String()
}
func (wf *WebFile) Stat() os.FileInfo {
return nil
}
var _ File = &WebFile{}
var _ FileInfo = &WebFile{}