CodeBlanks Logo Icon CodeBlanks

io.Reader

Learn the Reader interface and the Read method.

io.Reader

io.Reader is one of Go's most important interfaces; it has a single method:

type Reader interface {
    Read(p []byte) (n int, err error)
}

Read writes at most len(p) bytes into the given slice and returns how many it wrote. When data runs out it returns io.EOF. Files, network connections, HTTP bodies, strings.Reader and bytes.Buffer are all Readers, so the same code works on all of them.

io.ReadAll and wrappers

To read small data entirely, io.ReadAll(r) is enough. Readers can wrap each other: io.LimitReader(r, n) reads at most n bytes, io.MultiReader(a, b) reads one after another, and gzip.NewReader(r) decompresses data.

r := io.LimitReader(strings.NewReader("merhaba dünya"), 7)
b, _ := io.ReadAll(r)
fmt.Println(string(b))  // merhaba

Limiting an incoming body with LimitReader prevents memory attacks.

Practice Read in chunks

Read from strings.NewReader("gopher") in a loop with a 4-byte buffer. Print the piece read each time; leave the loop on io.EOF.

Starter code

main.go
package main

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

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

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

func main() {
    r := strings.NewReader("gopher")
    buf := make([]byte, 4)
    for {
        n, err := r.Read(buf)
        if n > 0 {
            fmt.Println(string(buf[:n]))
        }
        if err == io.EOF {
            break
        }
    }
}

Expected output

goph
er

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If <code>Read</code> returns both <code>n &gt; 0</code> and <code>io.EOF</code>, what should you do?

  • Panic as an error
  • Read again
  • Process the n bytes first, then stop reading Correct answer
  • Discard the bytes

Explanation: By contract, bytes read are always processed first; EOF only says no more data remains.

2 Data ended

Question
n, err := r.Read(buf)
if err == io.____ {
    break
}
Answer
n, err := r.Read(buf)
if err == io.EOF {
    break
}

Explanation: io.EOF is the special error reporting that no data is left to read.

3 Reader type

Term Meaning
os.File File
strings.Reader Text
http.Response.Body HTTP body
io.LimitReader Byte limit

All lessons in Intermediate