data_source.go (1943B)
1 // Copyright 2019 Unknwon 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations 13 // under the License. 14 15 package ini 16 17 import ( 18 "bytes" 19 "fmt" 20 "io" 21 "os" 22 ) 23 24 var ( 25 _ dataSource = (*sourceFile)(nil) 26 _ dataSource = (*sourceData)(nil) 27 _ dataSource = (*sourceReadCloser)(nil) 28 ) 29 30 // dataSource is an interface that returns object which can be read and closed. 31 type dataSource interface { 32 ReadCloser() (io.ReadCloser, error) 33 } 34 35 // sourceFile represents an object that contains content on the local file system. 36 type sourceFile struct { 37 name string 38 } 39 40 func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) { 41 return os.Open(s.name) 42 } 43 44 // sourceData represents an object that contains content in memory. 45 type sourceData struct { 46 data []byte 47 } 48 49 func (s *sourceData) ReadCloser() (io.ReadCloser, error) { 50 return io.NopCloser(bytes.NewReader(s.data)), nil 51 } 52 53 // sourceReadCloser represents an input stream with Close method. 54 type sourceReadCloser struct { 55 reader io.ReadCloser 56 } 57 58 func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { 59 return s.reader, nil 60 } 61 62 func parseDataSource(source interface{}) (dataSource, error) { 63 switch s := source.(type) { 64 case string: 65 return sourceFile{s}, nil 66 case []byte: 67 return &sourceData{s}, nil 68 case io.ReadCloser: 69 return &sourceReadCloser{s}, nil 70 case io.Reader: 71 return &sourceReadCloser{io.NopCloser(s)}, nil 72 default: 73 return nil, fmt.Errorf("error parsing data source: unknown type %q", s) 74 } 75 }