readerfile.go 1.38 KB
Newer Older
1 2
package files

3
import (
4
	"errors"
5 6
	"io"
	"os"
7
	"path/filepath"
8
)
9 10 11 12

// ReaderFile is a implementation of File created from an `io.Reader`.
// ReaderFiles are never directories, and can be read from and closed.
type ReaderFile struct {
13
	filename string
14
	fullpath string
15
	abspath  string
16 17 18 19
	reader   io.ReadCloser
	stat     os.FileInfo
}

20
func NewReaderFile(filename, path string, reader io.ReadCloser, stat os.FileInfo) *ReaderFile {
21 22 23 24 25 26 27 28 29 30
	return &ReaderFile{filename, path, path, reader, stat}
}

func NewReaderPathFile(filename, path string, reader io.ReadCloser, stat os.FileInfo) (*ReaderFile, error) {
	abspath, err := filepath.Abs(path)
	if err != nil {
		return nil, err
	}

	return &ReaderFile{filename, path, abspath, reader, stat}, nil
31 32 33 34 35 36 37 38 39 40 41
}

func (f *ReaderFile) IsDirectory() bool {
	return false
}

func (f *ReaderFile) NextFile() (File, error) {
	return nil, ErrNotDirectory
}

func (f *ReaderFile) FileName() string {
42
	return f.filename
43 44
}

45 46 47 48
func (f *ReaderFile) FullPath() string {
	return f.fullpath
}

49 50 51 52
func (f *ReaderFile) AbsPath() string {
	return f.abspath
}

53
func (f *ReaderFile) Read(p []byte) (int, error) {
54
	return f.reader.Read(p)
55 56 57
}

func (f *ReaderFile) Close() error {
58 59 60 61 62
	return f.reader.Close()
}

func (f *ReaderFile) Stat() os.FileInfo {
	return f.stat
63
}
64 65 66 67 68 69 70

func (f *ReaderFile) Size() (int64, error) {
	if f.stat == nil {
		return 0, errors.New("File size unknown")
	}
	return f.stat.Size(), nil
}