I would like to open a local file, and return a io.Reader
. The reason is that I need to feed a io.Reader
to a library I am using, like:
Use os.Open():
func Open(name string) (file *File, err error)
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.
The returned value of type *os.File
implements the io.Reader
interface.
os.Open
returns an io.Reader
http://play.golang.org/p/BskGT09kxL
package main
import (
"fmt"
"io"
"os"
)
var _ io.Reader = (*os.File)(nil)
func main() {
fmt.Println("Hello, playground")
}
The type *os.File implements the io.Reader interface, so you can return the file as a Reader. But I recommend you to use the bufio package if you have intentions of read big files, something like this:
file, err := os.Open("path/file.ext")
// if err != nil { ... }
return bufio.NewReader(file)
Here is an example where we open a text file and create an io.Reader from the returned *os.File instance f
package main
import (
"io"
"os"
)
func main() {
f, err := os.Open("somefile.txt")
if err != nil {
panic(err)
}
defer f.Close()
var r io.Reader
r = f
}