Repository navigation
Expand file tree
/
Copy pathdata_source.go
More file actions
74 lines (64 loc) · 1.64 KB
/
Copy pathdata_source.go
File metadata and controls
74 lines (64 loc) · 1.64 KB
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
package ini
import (
"bytes"
"fmt"
"io"
"os"
)
var (
_ dataSource = (*sourceFile)(nil)
_ dataSource = (*sourceData)(nil)
_ dataSource = (*sourceReadCloser)(nil)
)
// dataSource is an interface that returns object which can be read and closed.
type dataSource interface {
ReadCloser() (io.ReadCloser, error)
}
// sourceFile represents an object that contains content on the local file system.
type sourceFile struct {
name string
}
func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
return os.Open(s.name)
}
// sourceData represents an object that contains content in memory.
type sourceData struct {
data []byte
}
func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(s.data)), nil
}
// sourceReadCloser represents an input stream with Close method. A stream
// can be read only once, so its data is kept for reloading.
type sourceReadCloser struct {
reader io.ReadCloser
data []byte
err error
}
func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
if s.reader != nil {
s.data, s.err = io.ReadAll(s.reader)
if err := s.reader.Close(); s.err == nil {
s.err = err
}
s.reader = nil
}
if s.err != nil {
return nil, s.err
}
return io.NopCloser(bytes.NewReader(s.data)), nil
}
func newDataSource(source any) (dataSource, error) {
switch s := source.(type) {
case string:
return sourceFile{s}, nil
case []byte:
return &sourceData{s}, nil
case io.ReadCloser:
return &sourceReadCloser{reader: s}, nil
case io.Reader:
return &sourceReadCloser{reader: io.NopCloser(s)}, nil
default:
return nil, fmt.Errorf("error parsing data source: unknown type %q", s)
}
}