storj/pkg/ranger/file.go

41 lines
795 B
Go
Raw Normal View History

2018-04-24 03:16:34 +01:00
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package ranger
import (
"io"
"os"
)
2018-04-25 15:55:26 +01:00
// FileHandleRanger returns a Closer from a file handle. The
// Closer's Close method will call fh.Close().
2018-04-24 03:16:34 +01:00
// Footgun: If FileHandleRanger fails, fh.Close will not have been called.
2018-04-25 15:55:26 +01:00
func FileHandleRanger(fh *os.File) (Closer, error) {
2018-04-24 03:16:34 +01:00
stat, err := fh.Stat()
if err != nil {
return nil, Error.Wrap(err)
}
return struct {
Ranger
io.Closer
}{
Ranger: ReaderAtRanger(fh, stat.Size()),
Closer: fh,
}, nil
}
2018-04-25 15:55:26 +01:00
// FileRanger returns a Closer from a path.
func FileRanger(path string) (Closer, error) {
2018-04-24 03:16:34 +01:00
fh, err := os.Open(path)
if err != nil {
return nil, err
}
r, err := FileHandleRanger(fh)
if err != nil {
fh.Close()
return nil, err
}
return r, nil
}