...

Source file src/edge-infra.dev/pkg/lib/ini/data_source.go

Documentation: edge-infra.dev/pkg/lib/ini

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

View as plain text