In Go, the io.LimitedReader
type allows you to limit the number of bytes read from an input source. It wraps an io.Reader
and restricts the total number of bytes that can be read from it. Here's how to use it:
import (
"io"
"io/ioutil"
)
io.Reader
that represents your input source. It could be a file, network connection, or any other type that implements the io.Reader
interface. In this example, let's use a bytes.Buffer
as the input source:input := bytes.NewBufferString("Hello, World!")
io.LimitedReader
by providing the input source and the maximum number of bytes to be read:limit := int64(5) // Maximum of 5 bytes to be read
limitedReader := &io.LimitedReader{
R: input,
N: limit,
}
io.LimitedReader
using the io.ReadFull()
function or any other means of reading bytes from an io.Reader
:buffer := make([]byte, limit)
_, err := io.ReadFull(limitedReader, buffer)
if err != nil && err != io.ErrUnexpectedEOF {
// Handle the error
}
In this example, io.ReadFull()
attempts to read exactly limit
number of bytes into the buffer
. It returns io.ErrUnexpectedEOF
if fewer than limit
bytes are read.
fmt.Println(string(buffer))
In this case, it will print "Hello" as only the first 5 bytes were read.
By using io.LimitedReader
, you can restrict the number of bytes read from an input source without modifying the source itself.