os.Open

The Go function that opens a file for reading and returns an *os.File you can stream from and must close.

In more detail

Check the error, then write defer f.Close() on the next line so the file is closed on every path. An *os.File is an io.Reader, so it works with io.Copy and other stream helpers. os.Create is the matching call for writing.

Example

f, err := os.Open("app.log")
if err != nil { ... }
defer f.Close()

Related terms

Taught in

References