Create a io.Reader from a local file

Solution 1:

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

Solution 2:

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.

Solution 3:

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)

Solution 4:

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
}