-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurlreader.go
70 lines (64 loc) · 1.46 KB
/
urlreader.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
package iokit
import (
"errors"
"io"
"os"
"strings"
)
func (iourl IoUrl) openUrlReader() (rd io.ReadCloser, err error) {
if iourl.Cache.Exists() {
return iourl.Cache.Open()
}
var f Whole
if iourl.Cache.Defined() {
f, err = File(iourl.Cache.Path() + "~").Create()
} else {
f, err = Tempfile("url-noncached-*")
}
defer func() {
if f != nil {
f.End()
}
}()
if err = iourl.Download(f); err != nil {
return
}
if err = f.Commit(); err != nil {
return
}
if iourl.Cache.Defined() {
// file was closed in Commit call
if err = os.Rename(iourl.Cache.Path()+"~", iourl.Cache.Path()); err != nil {
return
}
if rd, err = File(iourl.Cache.Path()).Open(); err != nil {
return
}
} else {
rd = f.(io.ReadWriteCloser)
if _, err = rd.(io.Seeker).Seek(0, 0); err != nil {
return
}
f = nil // do not close tempfile, it will be removed on close later
}
return
}
type urlReader func (url string) interface {
Donload(writer) error
}
var UrlReaderFactory = map[string]func(string)interface{Download(io.Writer)error}{}
func Download(url string, writer io.Writer) error {
j := strings.Index(url, "://")
switch proto := strings.ToLower(url[:j]); proto {
case "http", "https":
return HttpUrl(url).Download(writer)
default:
if f, ok := UrlReaderFactory[proto]; ok {
return f(url).Download(writer)
}
return errors.New("can't read from url `" + url + "`")
}
}
func (iourl IoUrl) Download(wr io.Writer) error {
return Download(iourl.Url, wr)
}