Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a io.Reader from a local file

Tags:

go

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) {  } 
like image 835
Xi 张熹 Avatar asked Sep 05 '14 01:09

Xi 张熹


People also ask

What is an io reader?

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.

How do I read a file in Golang?

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.

What is reader and writer in Golang?

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) {}


1 Answers

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") } 
like image 153
fabrizioM Avatar answered Sep 17 '22 21:09

fabrizioM