storj/pkg/ranger/file.go

46 lines
901 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"
"go.uber.org/zap"
2018-04-24 03:16:34 +01:00
)
// FileHandleRanger returns a RangeCloser from a file handle. The
2018-04-25 15:55:26 +01:00
// 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.
func FileHandleRanger(fh *os.File) (RangeCloser, 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
}
// FileRanger returns a RangeCloser from a path.
func FileRanger(path string) (RangeCloser, 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 {
if closeErr := fh.Close(); closeErr != nil {
zap.S().Error(closeErr)
}
2018-04-24 03:16:34 +01:00
return nil, err
}
return r, nil
}