Repository navigation
Expand file tree
/
Copy pathdata_source.go
More file actions
77 lines (67 loc) · 1.63 KB
/
Copy pathdata_source.go
File metadata and controls
77 lines (67 loc) · 1.63 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
75
76
77
package ini
import (
"fmt"
"io"
"os"
)
var (
_ dataSource = (*sourceFile)(nil)
_ dataSource = (*sourceData)(nil)
_ dataSource = (*sourceReadCloser)(nil)
)
// dataSource is a source of INI input.
type dataSource interface {
// read returns the whole input.
read() (string, error)
}
// sourceFile represents an object that contains content on the local file system.
type sourceFile struct {
name string
}
func (s sourceFile) read() (string, error) {
data, err := os.ReadFile(s.name)
if err != nil {
return "", err
}
return string(data), nil
}
// sourceData represents an object that contains content in memory.
type sourceData struct {
data []byte
}
func (s *sourceData) read() (string, error) {
// Copy, as the caller may change the slice later.
return string(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 string
err error
}
func (s *sourceReadCloser) read() (string, error) {
if s.reader != nil {
data, err := io.ReadAll(s.reader)
s.data, s.err = string(data), err
if err := s.reader.Close(); s.err == nil {
s.err = err
}
s.reader = nil
}
return s.data, s.err
}
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)
}
}