data_source.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. package ini
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. )
  22. var (
  23. _ dataSource = (*sourceFile)(nil)
  24. _ dataSource = (*sourceData)(nil)
  25. _ dataSource = (*sourceReadCloser)(nil)
  26. )
  27. // dataSource is an interface that returns object which can be read and closed.
  28. type dataSource interface {
  29. ReadCloser() (io.ReadCloser, error)
  30. }
  31. // sourceFile represents an object that contains content on the local file system.
  32. type sourceFile struct {
  33. name string
  34. }
  35. func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
  36. return os.Open(s.name)
  37. }
  38. // sourceData represents an object that contains content in memory.
  39. type sourceData struct {
  40. data []byte
  41. }
  42. func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
  43. return ioutil.NopCloser(bytes.NewReader(s.data)), nil
  44. }
  45. // sourceReadCloser represents an input stream with Close method.
  46. type sourceReadCloser struct {
  47. reader io.ReadCloser
  48. }
  49. func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
  50. return s.reader, nil
  51. }
  52. func parseDataSource(source interface{}) (dataSource, error) {
  53. switch s := source.(type) {
  54. case string:
  55. return sourceFile{s}, nil
  56. case []byte:
  57. return &sourceData{s}, nil
  58. case io.ReadCloser:
  59. return &sourceReadCloser{s}, nil
  60. case io.Reader:
  61. return &sourceReadCloser{ioutil.NopCloser(s)}, nil
  62. default:
  63. return nil, fmt.Errorf("error parsing data source: unknown type %q", s)
  64. }
  65. }