github.com/yandex/pandora@v0.5.32/components/providers/http/provider.go (about) 1 package http 2 3 import ( 4 "bytes" 5 "io" 6 "strings" 7 8 "github.com/spf13/afero" 9 "github.com/yandex/pandora/components/providers/base" 10 "github.com/yandex/pandora/components/providers/http/config" 11 "github.com/yandex/pandora/components/providers/http/decoders" 12 "github.com/yandex/pandora/components/providers/http/provider" 13 "github.com/yandex/pandora/core" 14 "golang.org/x/xerrors" 15 ) 16 17 func NewProvider(fs afero.Fs, conf config.Config) (core.Provider, error) { 18 if !conf.Decoder.IsValid() { 19 return nil, xerrors.Errorf("unknown decoder type faced") 20 } 21 var ( 22 readSeeker io.ReadSeeker 23 closer io.Closer 24 err error 25 ) 26 if len(conf.Uris) > 0 { 27 readSeeker, closer, err = uriReadSeekCloser(conf) 28 } else { 29 readSeeker, closer, err = fileReadSeekCloser(fs, conf.File) 30 } 31 if err != nil { 32 return nil, xerrors.Errorf("cant create ReadSeekCloser: %w", err) 33 } 34 decoder, err := decoders.NewDecoder(conf, readSeeker) 35 if err != nil { 36 return nil, xerrors.Errorf("decoder init error: %w", err) 37 } 38 return &provider.Provider{ 39 ProviderBase: base.ProviderBase{ 40 FS: fs, 41 }, 42 Config: conf, 43 Decoder: decoder, 44 Close: closer.Close, 45 Sink: make(chan decoders.DecodedAmmo), 46 }, nil 47 } 48 49 func fileReadSeekCloser(fs afero.Fs, path string) (io.ReadSeeker, io.Closer, error) { 50 if path == "" { 51 return nil, nil, xerrors.Errorf("one should specify either 'file' or 'uris'") 52 } 53 file, err := fs.Open(path) 54 if err != nil { 55 return nil, nil, xerrors.Errorf("open file error: %w", err) 56 } 57 return file, file, nil 58 } 59 60 type fakeCloser struct { 61 } 62 63 func (fc *fakeCloser) Close() error { 64 return nil 65 } 66 67 func uriReadSeekCloser(conf config.Config) (io.ReadSeeker, io.Closer, error) { 68 if conf.Decoder != config.DecoderURI { 69 return nil, nil, xerrors.Errorf("'uris' expect setted only for 'uri' decoder, but faced with '%s'", conf.Decoder) 70 } 71 if conf.File != "" { 72 return nil, nil, xerrors.Errorf("one should specify either 'file' or 'uris', but not both of them") 73 } 74 reader := bytes.NewReader([]byte(strings.Join(conf.Uris, "\n"))) 75 readSeeker := io.ReadSeeker(reader) 76 77 return readSeeker, &fakeCloser{}, nil 78 }