-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl_opener.go
54 lines (43 loc) · 938 Bytes
/
url_opener.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
package sindri
import (
"archive/tar"
"context"
"fmt"
"io"
"net/url"
"strings"
xtar "github.com/frantjc/x/archive/tar"
)
type URLOpener interface {
Open(context.Context, *url.URL) (io.ReadCloser, error)
}
var (
urlMux = map[string]URLOpener{}
)
func Register(o URLOpener, scheme string, schemes ...string) {
for _, s := range append(schemes, scheme) {
if _, ok := urlMux[s]; ok {
panic("attempt to reregister scheme: " + s)
}
urlMux[s] = o
}
}
func Open(ctx context.Context, s string) (io.ReadCloser, error) {
u, err := url.Parse(s)
if err != nil {
return nil, err
}
o, ok := urlMux[strings.ToLower(u.Scheme)]
if !ok {
return nil, fmt.Errorf("no opener registered for scheme %s", u.Scheme)
}
return o.Open(ctx, u)
}
func Extract(ctx context.Context, s, dir string) error {
rc, err := Open(ctx, s)
if err != nil {
return err
}
defer rc.Close()
return xtar.Extract(tar.NewReader(rc), dir)
}