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.
|
|
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.