OSDN Git Service

Merge pull request #41 from Bytom/dev
[bytom/vapor.git] / vendor / github.com / ipfs / go-ipfs-files / webfile.go
1 package files
2
3 import (
4         "errors"
5         "io"
6         "net/http"
7         "net/url"
8 )
9
10 // WebFile is an implementation of File which reads it
11 // from a Web URL (http). A GET request will be performed
12 // against the source when calling Read().
13 type WebFile struct {
14         body          io.ReadCloser
15         url           *url.URL
16         contentLength int64
17 }
18
19 // NewWebFile creates a WebFile with the given URL, which
20 // will be used to perform the GET request on Read().
21 func NewWebFile(url *url.URL) *WebFile {
22         return &WebFile{
23                 url: url,
24         }
25 }
26
27 // Read reads the File from it's web location. On the first
28 // call to Read, a GET request will be performed against the
29 // WebFile's URL, using Go's default HTTP client. Any further
30 // reads will keep reading from the HTTP Request body.
31 func (wf *WebFile) Read(b []byte) (int, error) {
32         if wf.body == nil {
33                 resp, err := http.Get(wf.url.String())
34                 if err != nil {
35                         return 0, err
36                 }
37                 wf.body = resp.Body
38                 wf.contentLength = resp.ContentLength
39         }
40         return wf.body.Read(b)
41 }
42
43 // Close closes the WebFile (or the request body).
44 func (wf *WebFile) Close() error {
45         if wf.body == nil {
46                 return nil
47         }
48         return wf.body.Close()
49 }
50
51 // TODO: implement
52 func (wf *WebFile) Seek(offset int64, whence int) (int64, error) {
53         return 0, ErrNotSupported
54 }
55
56 func (wf *WebFile) Size() (int64, error) {
57         if wf.contentLength < 0 {
58                 return -1, errors.New("Content-Length hearer was not set")
59         }
60
61         return wf.contentLength, nil
62 }
63
64 var _ File = &WebFile{}