...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ini
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "io/ioutil"
22 "os"
23 )
24
25 var (
26 _ dataSource = (*sourceFile)(nil)
27 _ dataSource = (*sourceData)(nil)
28 _ dataSource = (*sourceReadCloser)(nil)
29 )
30
31
32 type dataSource interface {
33 ReadCloser() (io.ReadCloser, error)
34 }
35
36
37 type sourceFile struct {
38 name string
39 }
40
41 func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
42 return os.Open(s.name)
43 }
44
45
46 type sourceData struct {
47 data []byte
48 }
49
50 func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
51 return ioutil.NopCloser(bytes.NewReader(s.data)), nil
52 }
53
54
55 type sourceReadCloser struct {
56 reader io.ReadCloser
57 }
58
59 func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
60 return s.reader, nil
61 }
62
63 func parseDataSource(source interface{}) (dataSource, error) {
64 switch s := source.(type) {
65 case string:
66 return sourceFile{s}, nil
67 case []byte:
68 return &sourceData{s}, nil
69 case io.ReadCloser:
70 return &sourceReadCloser{s}, nil
71 case io.Reader:
72 return &sourceReadCloser{ioutil.NopCloser(s)}, nil
73 default:
74 return nil, fmt.Errorf("error parsing data source: unknown type %q", s)
75 }
76 }
77
View as plain text