Reading exactly n bytes

In the previous example, File.Read() will not return an error if a file only contains 10 bytes, but you provide a byte slice buffer with 500 bytes. There are some occasions where you want to ensure that the entire buffer is filled up. The io.ReadFull() function will return an error if the entire buffer is not filled up. If io.ReadFull() does not have any data to read, an EOF error is returned. If it reads some data, but then encounters an EOF, it will return an ErrUnexpectedEOF error:

package main 
 
import ( 
   "io" 
   "log" 
   "os" 
) 
 
func main() { 
   // Open file for reading 
   file, err := os.Open("test.txt") 
   if err != nil { 
      log.Fatal(err) 
   } 
 
   // The file.Read() function will happily read a tiny file in to a     // large byte slice, but ...

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.