Quickly reading whole files to memory

Similar to the io.ReadAll() function in the previous example, io.ReadFile() will read all the bytes in a file and return a byte slice. The primary difference between the two is that io.ReadFile() expects a file path, not a file object that has already been opened. The io.ReadFile() function will take care of opening, reading, and closing the file. You just provide a filename and it provides the bytes. This is often the quickest and easiest method to load file data.

While this method is very convenient, it has limitations; because it reads the entire file directly to memory, very large files may exhaust a system's memory limit:

package main import ( "io/ioutil" "log" ) func main() { // Read file to byte ...

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.