ipfs-cluster/api/rest/client/webfile.go
Hector Sanjuan b6182e0621 rest/client: Implement .Add(paths), which adds from local files and web files
.Add(paths) will interpret http* paths as WebFiles. These are read performing
a GET request to the location. Otherwise, the path is interpreted as a local
disk file/folder, and read from disk. ipfs-cluster-ctl has been updated
accordingly.

License: MIT
Signed-off-by: Hector Sanjuan <code@hector.link>
2018-08-20 11:07:23 +02:00

58 lines
889 B
Go

package client
import (
"io"
"net/http"
"net/url"
"path/filepath"
"github.com/ipfs/go-ipfs-cmdkit/files"
)
// To be submitted to cmdkit/files.
type webFile struct {
body io.ReadCloser
url *url.URL
}
func newWebFile(url *url.URL) *webFile {
return &webFile{
url: url,
}
}
func (wf *webFile) Read(b []byte) (int, error) {
if wf.body == nil {
resp, err := http.Get(wf.url.String())
if err != nil {
return 0, err
}
wf.body = resp.Body
}
return wf.body.Read(b)
}
func (wf *webFile) Close() error {
if wf.body == nil {
return nil
}
return wf.body.Close()
}
func (wf *webFile) FullPath() string {
return wf.url.Host + wf.url.Path
}
func (wf *webFile) FileName() string {
return filepath.Base(wf.url.Path)
}
func (wf *webFile) IsDirectory() bool {
return false
}
func (wf *webFile) NextFile() (files.File, error) {
return nil, files.ErrNotDirectory
}