It’s a common case to download a file with full size, but what if we want to download only the first few bytes of the file? For example if we want to check the file header or to check the file existence.

Should we download file to buffer and copy it to local disk by counting bytes? No, Go offers a super easy function to handle this, io.Copy().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func copyMax(dst io.Writer, src io.Reader, n int64) error {
_, err := io.CopyN(dst, src, n)
if err != nil {
// If there's less data available
// it will throw the error "io.EOF"
return err
}

// Take one more byte
// to check if there's more data available
nextByte := make([]byte, 1)
nRead, _ := io.ReadFull(src, nextByte)
if nRead > 0 {
// Yep, there's too much data
return nil
}

// Exactly the same amount of data
return nil
}