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:
func read(r io.Reader) (results []string) { }
The io.Reader interface is used by many packages in the Go standard library and it represents the ability to read a stream of data. More specifically allows you to read data from something that implements the io.Reader interface into a slice of bytes.
The simplest way of reading a text or binary file in Go is to use the ReadFile() function from the os package. This function reads the entire content of the file into a byte slice, so you should be careful when trying to read a large file - in this case, you should read the file line by line or in chunks.
Reader/Writer are basic interfaces designed in Golang. For example, if a struct have a function like: type Example struct { }func (e *Example) Write(p byte[]) (n int, err error) {}func (e *Example) Read(p byte[]) (n int, err error) {}
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With