Skip to main content

io.LimitReader

This is a simple one! Let's assume you want to read from a Reader, but you only want to read the first 4 bytes.

For cases like these, we can use io.LimitReader:

func LimitReader(r Reader, n int64) Reader

LimitReader returns a Reader that reads from r but stops with EOF after n bytes. The underlying implementation is a * LimitedReader.

Bellow, we have an example where we write into os.Stdout(which is an io.Writer) only 4 bytes:

package main

import (
"io"
"log"
"os"
"strings"
)

func main() {
r := strings.NewReader("Hello!")

lr := io.LimitReader(r, 4)

if _, err := io.Copy(os.Stdout, lr); err != nil {
log.Fatal(err)
}
}

run in Playground

Output:

Hell

And this limit is kept whatever function you use to read from a LimitReader. If you use io.ReadAll for example, you are still limited to reading only 4 bytes:

package main

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

func main() {
r := strings.NewReader("Hello!")

lr := io.LimitReader(r, 4)

data, err := io.ReadAll(lr)
if err != nil {
log.Fatal(err)
}

fmt.Println(string(data))
}

run in Playground

Output:

Hell