Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Read and Stream With io.Reader and io.Writer

Process files and network streams in bounded memory using bufio.Scanner, io.Copy, and io.LimitReader. After this, you can handle large payloads without loading them all into RAM.

Course content

Sign in to save your progress.

Course Home

If an HTTP handler reads an uploaded 1.5 GB CSV file with io.ReadAll(r.Body), Go allocates 1.5 GB of RAM before parsing the very first row. Five concurrent uploads like that OOM-kill an 8 GB container. Go's standard library avoids buffering entire payloads by streaming data in small fixed chunks through two one-method interfaces: io.Reader and io.Writer.

Skip ahead

If you already stream payloads with io.Copy, bound untrusted inputs with io.LimitReader or http.MaxBytesReader, and compose pipelines with io.TeeReader, take the section quiz or continue to "Use context.Context for Deadlines and Cancellation."

Experiment 1: Why io.Copy keeps memory flat

Files (*os.File), HTTP request bodies (r.Body), HTTP response writers (w), gzip streams, SHA-256 hashers, and bytes.Buffer all implement io.Reader or io.Writer. Because they share the exact same Read([]byte) / Write([]byte) contract, io.Copy(dst, src) copies chunks through a single 32 KB buffer until io.EOF—whether the stream is 50 bytes or 50 gigabytes:

// Bad for large uploads: loads the entire stream into RAM
data, err := io.ReadAll(r.Body)

// Good: streams 32 KB at a time directly to disk
n, err := io.Copy(dstFile, r.Body)

Experiment 2: Bounding untrusted streams with io.LimitReader

Even when streaming, an untrusted client can keep sending bytes forever to fill your disk or tie up a worker. Wrapping any io.Reader in io.LimitReader(src, maxBytes) stops reading cleanly after maxBytes with zero extra buffer allocation:

package main

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

func main() {
	src := strings.NewReader("header:payload-that-keeps-going")
	var dst bytes.Buffer
	n, err := io.Copy(&dst, io.LimitReader(src, 14))
	fmt.Printf("copied=%d err=%v data=%q\n", n, err, dst.String())
}
copied=14 err=<nil> data="header:payload"

Notice what io.LimitReader did at byte 14: it returned io.EOF, and io.Copy treated io.EOF as normal end-of-stream (returning err == nil). If you need to detect when a payload exceeded 14 bytes, read up to limit + 1 bytes—or in HTTP handlers, use http.MaxBytesReader(w, r.Body, limit), which returns a typed *http.MaxBytesError so you can reply with 413 Payload Too Large.

Experiment 3: Hashing a file while saving it with io.TeeReader

Suppose your upload endpoint needs to save a user's file to disk and compute its SHA-256 checksum for integrity verification. The naive approach saves the file first, then re-opens and reads the entire file a second time! With io.TeeReader, every byte read from src is automatically mirrored into the SHA-256 hasher on the exact same pass:

package main

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"io"
	"strings"
)

func main() {
	src := strings.NewReader("invoice,1200\nshipping,150\n")
	h := sha256.New()
	var disk bytes.Buffer

	n, err := io.Copy(&disk, io.TeeReader(src, h))
	fmt.Printf("bytes=%d err=%v sha256=%x\n", n, err, h.Sum(nil)[:8])
}
bytes=26 err=<nil> sha256=330bb2a2ea1bbbb3

One pass over the stream, ~32 KB of RAM total, both the saved output and the checksum ready when io.Copy returns.

Experiment 4: Line-by-line reading and the 64 KB bufio.Scanner trap

For line-oriented log or CSV files, bufio.NewScanner(r) is fast and ergonomic—just watch out for two things: always check if err := scanner.Err(); err != nil after the loop, and remember its default maximum line length is 64 KB. If a minified JSON log line is 200 KB long, scanner.Scan() stops early and sets bufio.ErrTooLong unless you raise the limit with scanner.Buffer(make([]byte, 64*1024), 1024*1024).

Common mistakes

  • Calling io.ReadAll(r.Body) on public HTTP endpoints: Lets one client stream a 1 GB body straight into heap memory. Always cap first with http.MaxBytesReader.
  • Ignoring the error returned by file.Close() after writing: The OS buffers file writes in page cache; a disk-full error may only surface when Close() flushes!
  • Forgetting resp.Body.Close() on HTTP client responses: Even if you never read the body, leaving resp.Body open leaks the underlying TCP connection from the keep-alive pool.

💡 Tip

Write parsers to accept io.Reader instead of a filename (func ParseCSV(r io.Reader) instead of func ParseCSV(path string)). Your unit tests can then pass strings.NewReader("a,b\n1,2\n") directly in memory with zero temp files.

What happens if you skip this step

Services built on os.ReadFile and io.ReadAll pass unit tests on 2 KB fixtures and then OOM-crash in production the first time a customer uploads a 500 MB export or a handful of large requests arrive concurrently.

Your endpoint saves an uploaded 2 GB backup file and records its SHA-256 digest. How does io.TeeReader let you compute the checksum without reading the 2 GB file twice or loading it into RAM?

About

Process files and network streams in bounded memory using bufio.Scanner, io.Copy, and io.LimitReader. After this, you can handle large payloads without loading them all into RAM.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.