Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

✋ Limit read bytes using io.LimitedReader in Go

io

Please consider supporting us by disabling your ad blocker

There are situations when you want to limit the number of bytes read, e.g., from a server response or a file. In such a case, you can count bytes during reading and stop the process at the right moment. However, there are simpler methods in Go. Using the io.LimitedReader wrapper, you can read the set number of bytes from the underlying reader without modifying the reading code, as it creates a new io.Reader limited to a fixed number of N bytes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "strings"
)

func main() {
    r := strings.NewReader("https://gosamples.dev")

    limitedReader := &io.LimitedReader{R: r, N: 8}
    body, err := ioutil.ReadAll(limitedReader)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(body))
}

Output:

https://

Look at the example. In the main() function, we initialize a simple strings.Reader that contains an URL, and we want to read the first 8 bytes from it. To do this, we create a new io.LimitedReader in line 14 that takes the underlying io.Reader and the number of bytes to read as arguments. As a result, when reading data from this stream, we will not get more than the set number of N bytes.