-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
102 lines (75 loc) · 2.55 KB
/
writer.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
90
91
92
93
94
95
96
97
98
99
100
101
102
package writer
import (
"context"
"fmt"
"github.com/aaronland/go-roster"
"io"
"net/url"
"sort"
"strings"
)
var writer_roster roster.Roster
// WriterInitializationFunc is a function defined by individual writer package and used to create
// an instance of that writer
type WriterInitializationFunc func(ctx context.Context, uri string) (Writer, error)
// Writer is an interface for writing data to multiple sources or targets.
type Writer interface {
// Writer copies the contents of an `io.ReadSeeker` instance to a relative path.
// The absolute path for the file is determined by the instance implementing the `Writer` interface.
Write(context.Context, string, io.ReadSeeker) (int64, error)
// WriterURI returns the absolute URI for an instance implementing the `Writer` interface.
WriterURI(context.Context, string) string
// Close closes any underlying writing mechnisms for an instance implementing the `Writer` interface.
Close(context.Context) error
}
// RegisterWriter registers 'scheme' as a key pointing to 'init_func' in an internal lookup table
// used to create new `Writer` instances by the `NewWriter` method.
func RegisterWriter(ctx context.Context, scheme string, init_func WriterInitializationFunc) error {
err := ensureWriterRoster()
if err != nil {
return err
}
return writer_roster.Register(ctx, scheme, init_func)
}
func ensureWriterRoster() error {
if writer_roster == nil {
r, err := roster.NewDefaultRoster()
if err != nil {
return err
}
writer_roster = r
}
return nil
}
// NewWriter returns a new `Writer` instance configured by 'uri'. The value of 'uri' is parsed
// as a `url.URL` and its scheme is used as the key for a corresponding `WriterInitializationFunc`
// function used to instantiate the new `Writer`. It is assumed that the scheme (and initialization
// function) have been registered by the `RegisterWriter` method.
func NewWriter(ctx context.Context, uri string) (Writer, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, err
}
scheme := u.Scheme
i, err := writer_roster.Driver(ctx, scheme)
if err != nil {
return nil, err
}
init_func := i.(WriterInitializationFunc)
return init_func(ctx, uri)
}
// Schemes returns the list of schemes that have been registered.
func Schemes() []string {
ctx := context.Background()
schemes := []string{}
err := ensureWriterRoster()
if err != nil {
return schemes
}
for _, dr := range writer_roster.Drivers(ctx) {
scheme := fmt.Sprintf("%s://", strings.ToLower(dr))
schemes = append(schemes, scheme)
}
sort.Strings(schemes)
return schemes
}