Skip to content

The io Package: Readers, Writers, Pipes & Composition ​

"Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors." — Go standard library, package io, documentation of io.Reader (Go 1.25 source)

Summary: io.Reader and io.Writer are two one-method interfaces that every byte source and sink in Go implements (files, sockets, HTTP bodies, gzip, hashes, buffers), so code written against them composes like pipe fittings and streams any size of data in constant memory. Focus: the exact Read/Write contracts (n > 0 with err, io.EOF, partial reads, short writes), io.ReadFull/ReadAtLeast/ReadAll, Closer and its combinations, io.Copy and its WriterTo/ReaderFrom fast paths down to sendfile and splice, io.Pipe, the adapter set (MultiReader, MultiWriter, TeeReader, LimitReader, SectionReader, NopCloser, Discard), Seeker and whence, bufio, bytes.Buffer/strings.Reader/bytes.Reader, HTTP bodies as streams, deadlines instead of context, testing with iotest, and writing your own Reader. Learning goal: Write read loops that never lose the last chunk, compose gzip/tar/JSON/HTTP streams without loading them into memory, cap untrusted input, pick the right adapter or buffer for each job, make copies hit the kernel fast path, and prove a custom Reader correct with iotest.TestReader.

This page is the complete reference for Go's byte-stream interfaces and the standard pieces built on them. It owns the language and stdlib mechanics of streaming. Files, directories, paths and embed are in Files, Directories, Paths, Temp Files, bufio & embed (this page covers bufio as a wrapper, not file handling); JSON struct tags and encoder options are in JSON, XML, Struct Tags, Encoder/Decoder, Base64; hash algorithms are in Hashing & Crypto; the HTTP server and client themselves are in net/http: Server, Client, 1.22 Routing; cancellation is in context; interfaces and embedding in general are in Interfaces, Type Assertions, Type Switches & any. Compression algorithms are explained in Compression, sockets in Ports, Sockets & Connections, and broker-level flow control in Backpressure & Flow Control.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why two tiny interfaces run everythingWhy it exists
Go 1, ioutil deprecation, 1.22 fast pathsWhere it comes from
n > 0 with err, partial readsio.Reader and the Read contract
io.EOF, 0, nilio.EOF and the end of a stream
io.ReadFull, io.ReadAtLeast, io.ErrUnexpectedEOFReading an exact amount
io.ReadAll and memoryio.ReadAll
io.ErrShortWrite, StringWriterio.Writer and short writes
Close, ReadCloser, WriteCloserio.Closer and its combinations
io.Copy, io.CopyN, io.CopyBufferCopying
WriterTo, ReaderFrom, sendfile, spliceFast paths and zero-copy
io.Pipe, CloseWithError, io.ErrClosedPipeio.Pipe
MultiReader, TeeReader, LimitReader, NopCloser, DiscardThe adapter set
Seek, SeekStart, SeekCurrent, SeekEnd, SectionReaderSeeker and random access
bufio.Reader, bufio.Writer, Scanner, Flushbufio
bytes.Buffer, strings.Reader, bytes.ReaderIn-memory readers and writers
Counting writer, hashing writer, FprintfWriter adapters
Implementing Read yourselfA custom Reader
Timeouts, cancellation, SetReadDeadlineDeadlines and context
testing/iotestTesting readers
io.Reader versus iter.SeqReaders and iterators
Exact error textsMechanics
tar.gz, streaming JSON, HTTP bodies, chunksSolving the classic problems
PHP streams, php://temp, stream filtersFor PHP/Laravel developers
Reproduce the outputsLab

Everything in one minute ​

The interfaces.

InterfaceMethodIn plain wordsImplemented by
io.ReaderRead(p []byte) (n int, err error)Fill up to len(p) bytes, say how many*os.File, net.Conn, http.Request.Body, gzip.Reader, strings.Reader
io.WriterWrite(p []byte) (n int, err error)Take all of p or return an error*os.File, net.Conn, http.ResponseWriter, hash.Hash, bytes.Buffer
io.CloserClose() errorRelease the resource, flush trailersfiles, sockets, bodies, gzip.Writer
io.SeekerSeek(offset int64, whence int) (int64, error)Move the cursor*os.File, bytes.Reader, strings.Reader, io.SectionReader
io.ReaderAtReadAt(p []byte, off int64)Read at an offset, parallel-safe*os.File, bytes.Reader, strings.Reader
io.WriterToWriteTo(w Writer) (int64, error)"I can push myself into w efficiently"bytes.Buffer, strings.Reader, *os.File, *net.TCPConn
io.ReaderFromReadFrom(r Reader) (int64, error)"I can pull from r efficiently"bytes.Buffer, *os.File, *net.TCPConn, bufio.Writer, io.Discard
io.StringWriterWriteString(s string) (int, error)Write a string without convertingbytes.Buffer, strings.Builder, bufio.Writer, *os.File
ReadCloser, WriteCloser, ReadSeeker, ReadWriter...embedded combinationsExactly the union of the partsas above

The helpers.

HelperWhat it doesEnds with
io.Copy(dst, src)Stream src into dst until EOFerr == nil on success, not io.EOF
io.CopyN(dst, src, n)Copy exactly n bytesio.EOF if src was shorter
io.CopyBuffer(dst, src, buf)Copy through your bufferpanics if len(buf) == 0
io.ReadFull(r, buf)Fill buf completelyio.ErrUnexpectedEOF if cut in the middle
io.ReadAtLeast(r, buf, min)Read at least min bytesio.ErrShortBuffer if min > len(buf)
io.ReadAll(r)Everything into one slicememory = input size
io.WriteString(w, s)Uses WriteString if present
io.LimitReader(r, n)EOF after n bytessilent truncation
io.TeeReader(r, w)Every byte read is also written to wwrite errors become read errors
io.MultiReader(rs...)Concatenate readers
io.MultiWriter(ws...)Duplicate each writestops at the first failing writer
io.NewSectionReader(ra, off, n)Window over a ReaderAt
io.Pipe()Synchronous in-memory pipeneeds two goroutines
io.NopCloser(r)Add a no-op Close
io.DiscardWriter that swallows everything

The errors.

ErrorTextMeaning
io.EOFEOFGraceful end of input; compare with == or errors.Is
io.ErrUnexpectedEOFunexpected EOFInput ended inside a fixed-size block
io.ErrShortWriteshort writeA Writer took fewer bytes and returned no error
io.ErrShortBuffershort bufferThe buffer you passed is too small
io.ErrClosedPipeio: read/write on closed pipeOther end of an io.Pipe was closed
io.ErrNoProgressmultiple Read calls return no data or errorA broken Reader keeps returning 0, nil
*http.MaxBytesErrorhttp: request body too largeBody went past http.MaxBytesReader
bufio.ErrTooLongbufio.Scanner: token too longA line exceeded the Scanner's buffer

Why it exists ​

Every program moves bytes between places that have nothing in common: a disk, a TCP socket, a decompressor, a hash, a test buffer. If each had its own API, every combination would need its own glue code and every large input would be loaded into memory first. Go defines the smallest possible contract, one method that fills a slice and one that drains a slice, and lets everything implement it. Code that accepts an io.Reader works with all present and future sources, and data flows through in fixed-size pieces.

Simpler, smallerRicher, faster
One-method interfaces: easy to implement, easy to fake in testsOptional extra interfaces (WriterTo, ReaderFrom, ReaderAt, StringWriter) discovered at run time
Caller owns the buffer: no allocation per callCaller must handle partial reads correctly
Streaming: memory independent of input sizeNo random access unless the source also offers Seeker/ReaderAt
No context parameter: interfaces stay tinyCancellation needs deadlines or wrappers
Errors are values: io.EOF is a sentinelEasy to treat io.EOF as a failure or miss data that came with it

An everyday picture. Think of plumbing. A Reader is a tap: each turn gives you some water, never more than your bucket holds, sometimes less. A Writer is a drain. io.Copy is a hose between them. Adapters are fittings: a meter (counting writer), a T-piece (TeeReader, MultiWriter), a flow limiter (LimitReader), a filter (gzip). Because every fitting has the same thread, you screw them together in any order, and the amount of water in the pipes at any moment is a few buckets, no matter how big the reservoir. We reuse this picture throughout.

Three common misunderstandings, up front ​

  1. "Read fills my buffer." It reads up to len(p) bytes and "conventionally returns what is available instead of waiting for more". A network read of a 10 KB message can return 1 byte, then 4 KB, then the rest. Use io.ReadFull when you need exactly n.
  2. "If err != nil I can ignore n." A Reader may return the last bytes and io.EOF in the same call. Checking the error first throws those bytes away (io.Reader and the Read contract).
  3. "io.ReadAll is fine, the body is small." Small today, attacker-controlled tomorrow. Any input you do not control needs a limit (io.LimitReader, http.MaxBytesReader) or a streaming decoder.

Where it comes from ​

The interfaces are part of Go 1 and have not changed since; the authoritative text is the package documentation in the Go source (src/io/io.go, pipe.go, multi.go), which this page quotes from the Go 1.25 tag because pkg.go.dev refused automated fetches. Effective Go uses them as its model of small interfaces: "Interfaces with only one or two methods are common in Go code, and are usually given a name derived from the method, such as io.Writer for something that implements Write", and builds io.ReadWriter by embedding Reader and Writer. The same document notes that Fprintf "can generate output to anything with a Write method".

Later milestones, each from the release notes:

VersionChange
Go 1.16io/ioutil deprecated: "All functionality provided by the package has been moved to other packages"; ioutil.ReadAll became io.ReadAll, ioutil.NopCloser became io.NopCloser, ioutil.Discard became io.Discard
Go 1.19http.MaxBytesReader returns the typed error *http.MaxBytesError
Go 1.20io.OffsetWriter (the write-side twin of SectionReader)
Go 1.21context.AfterFunc, useful to turn cancellation into a deadline
Go 1.22io.Copy from a TCPConn to a UnixConn uses splice(2) via TCPConn.WriteTo; from a File to a net.UnixConn uses sendfile(2) via File.WriteTo (Linux)
Go 1.23range-over-func iterators (iter.Seq), the typed alternative to a byte stream

The test helpers in testing/iotest (OneByteReader, HalfReader, DataErrReader, TimeoutReader, ErrReader, TestReader) exist precisely because the Read contract allows so many shapes of correct behaviour.

The concept catalogue ​

io.Reader and the Read contract Must-know ​

In plain words: you hand Read an empty bucket; it puts some bytes in (between zero and the bucket size), tells you how many, and maybe also tells you something went wrong or the source is finished. Use the bytes first, then look at the error.

Common misunderstanding: "n is meaningless when err != nil." The contract says the opposite: when an error happens "after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call."

Definition: Read(p []byte) (n int, err error) reads up to len(p) bytes into p, with 0 <= n <= len(p). It may use all of p as scratch space. If some data is available but not len(p) bytes, it conventionally returns what is available. If len(p) == 0 it returns n == 0. Returning 0, nil is discouraged and means "nothing happened", not EOF. "Implementations must not retain p." Unless documented otherwise, a Reader is not safe for parallel use (package doc: "clients should not assume they are safe for parallel execution").

     caller                         Reader (5 bytes left, then end)
1    n, err := r.Read(buf[:512])
2                                   copies 5 bytes, returns 5, io.EOF   (allowed)
3    total += n        // 5 bytes used
4    err == io.EOF -> stop, success
     -- the other legal shape --
2'                                  returns 5, nil
3'   total += n
4'   n, err = r.Read(buf)           returns 0, io.EOF
5'   stop, success
     -- the bug --
2"   if err != nil { return }       5 bytes from line 2 are lost
n, err := r.Read(p)0 <= n <= len(p)n > 0, err == nilpartial read is normaln > 0, err == io.EOFlast bytes plus the endn == 0, err == io.EOFgraceful end of inputn >= 0, other errfailure, maybe after data1. use p[:n] firstalways, before err2. then check errnil: call Read againerr == io.EOF:stop, report successreturn err (wrap it);bytes already used stay used

Real scenario: a log shipper that drops the last line of every file; a TCP framing layer that assumes one Read equals one message and breaks under load when Nagle or TLS records split it; a checksum that differs from sha256sum by the final block; a custom Reader that returns 0, nil forever and makes bufio give up with io.ErrNoProgress.

ReturnMeaningCaller action
n > 0, nilData, more may followUse p[:n], read again
n > 0, io.EOFLast data and the endUse p[:n], stop with success
0, io.EOFEndStop with success
n >= 0, other errFailure, maybe after dataUse p[:n] if meaningful, return err
0, nilNothing happened (discouraged)Read again; do not treat as EOF

Fix / how to use it: the correct loop and the buggy one side by side; the test feeds both a DataErrReader, which returns the final bytes together with io.EOF, and the buggy loop counts 0 of 13 bytes.

go
// Package contract shows the io.Reader contract from the caller's side:
// process n > 0 bytes before looking at err, treat io.EOF as the normal end,
// and use io.ReadFull / io.ReadAtLeast when a fixed number of bytes is required.
package contract

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
)

// CountBytes reads r to the end with a small buffer and returns the byte count.
// It is the canonical read loop: bytes first, then the error.
func CountBytes(r io.Reader) (int64, error) {
	buf := make([]byte, 512)
	var total int64
	for {
		n, err := r.Read(buf)
		total += int64(n) // always consume n before err
		if err == io.EOF {
			return total, nil // graceful end of input
		}
		if err != nil {
			return total, err // real failure, possibly after some bytes
		}
	}
}

// CountBytesWrong is the common bug: it checks err first and drops the
// last chunk when a Reader returns data together with io.EOF.
func CountBytesWrong(r io.Reader) (int64, error) {
	buf := make([]byte, 512)
	var total int64
	for {
		n, err := r.Read(buf)
		if err != nil {
			if err == io.EOF {
				return total, nil
			}
			return total, err
		}
		total += int64(n)
	}
}

// ErrBadFrame is returned when a frame header promises more bytes than exist.
var ErrBadFrame = errors.New("contract: truncated frame")

// ReadFrame reads one length-prefixed frame: a 4-byte big-endian length then
// that many bytes. io.ReadFull turns "stream ended in the middle" into
// io.ErrUnexpectedEOF, which a plain Read loop would miss.
func ReadFrame(r io.Reader, max uint32) ([]byte, error) {
	var hdr [4]byte
	if _, err := io.ReadFull(r, hdr[:]); err != nil {
		return nil, err // io.EOF here means "no more frames": clean end
	}
	size := binary.BigEndian.Uint32(hdr[:])
	if size > max {
		return nil, fmt.Errorf("contract: frame of %d bytes exceeds %d", size, max)
	}
	body := make([]byte, size)
	if _, err := io.ReadFull(r, body); err != nil {
		if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
			return nil, fmt.Errorf("%w: %w", ErrBadFrame, io.ErrUnexpectedEOF)
		}
		return nil, err
	}
	return body, nil
}

// WriteFrame writes the frame format that ReadFrame reads.
func WriteFrame(w io.Writer, payload []byte) error {
	var hdr [4]byte
	binary.BigEndian.PutUint32(hdr[:], uint32(len(payload)))
	if _, err := w.Write(hdr[:]); err != nil {
		return err
	}
	_, err := w.Write(payload)
	return err
}

// ReadHeader needs at least min bytes (a magic number) but accepts more if
// they are already available; io.ReadAtLeast expresses exactly that.
func ReadHeader(r io.Reader, buf []byte, min int) (int, error) {
	return io.ReadAtLeast(r, buf, min)
}
$ go test -run 'TestCountBytes' -v ./contract
    contract_test.go:24: correct loop: 13 bytes, err-first loop: 0 bytes
--- PASS: TestCountBytesHandlesDataWithEOF (0.00s)

io.EOF and the end of a stream Must-know ​

In plain words: io.EOF is not an error in the "something broke" sense. It is the signal "there is nothing more". Helpers that read "until the end" (io.Copy, io.ReadAll, json.Decoder at top level) swallow it and return nil.

Common misunderstanding: "I can wrap io.EOF like any error." A Reader must return io.EOF itself: the doc says "Read must return EOF itself, not an error wrapping EOF, because callers will test for EOF using ==". Wrapping is fine in your functions' results (callers use errors.Is), not inside Read.

Definition: var EOF = errors.New("EOF"). "Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more detail."

1   frames, err := readAll(conn)       // reads frames until io.EOF
2   peer closes after 3 full frames    -> io.EOF   -> success, 3 frames
3   peer dies in the middle of frame 4 -> header said 100 bytes, got 40
4   ReadFull returns io.ErrUnexpectedEOF -> failure, not "end"

Real scenario: a CSV import that reports "done" when the upload was cut in half; a protocol client that reconnects on io.EOF but should alert on ErrUnexpectedEOF; a gzip reader that returns unexpected EOF for a truncated download.

SituationCorrect error
No more records, clean boundaryio.EOF
Stream ended inside a recordio.ErrUnexpectedEOF
Stream ended inside a gzip memberunexpected EOF from compress/gzip
Peer reset the TCP connectionread: connection reset by peer (a *net.OpError)
JSON value incompleteunexpected EOF from encoding/json

Reading an exact amount: io.ReadFull and io.ReadAtLeast Must-know ​

In plain words: when a format says "the next 4 bytes are the length", one Read is not enough; io.ReadFull keeps calling Read until the buffer is full or the stream ends, and tells you which.

Common misunderstanding: "ReadFull returns io.EOF whenever the stream ends." Only if no byte was read. If it got some but not all, it returns io.ErrUnexpectedEOF. That difference is how you tell "no more frames" from "a frame was cut".

Definition: ReadFull(r, buf) "reads exactly len(buf) bytes from r into buf ... The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil." ReadAtLeast(r, buf, min) reads at least min bytes (it may read more, up to len(buf)); if min > len(buf) it returns io.ErrShortBuffer.

     ReadFull(r, buf[:8]) over a reader that yields 3, then 3, then EOF
1    Read -> 3 bytes            total 3
2    Read -> 3 bytes            total 6
3    Read -> 0, io.EOF          total 6 < 8
4    return 6, io.ErrUnexpectedEOF

Real scenario: length-prefixed frames (the snippet's ReadFrame), binary headers (PNG signature, WAL record headers), fixed-size chunks for multipart uploads, reading a magic number with ReadAtLeast while accepting more bytes if already buffered.

CallEmpty inputPartial inputEnough input
r.Read(buf)0, io.EOFk, nil or k, io.EOFany n <= len(buf)
io.ReadFull(r, buf)0, io.EOFk, io.ErrUnexpectedEOFlen(buf), nil
io.ReadAtLeast(r, buf, min)0, io.EOFk, io.ErrUnexpectedEOFn >= min, nil
io.ReadAtLeast with min > len(buf)0, io.ErrShortBuffersamesame

The test TestFrames wraps the source in iotest.OneByteReader so every Read returns one byte, and ReadFrame still assembles whole frames; TestTruncatedFrame cuts three bytes and gets contract: truncated frame: unexpected EOF.

io.ReadAll and memory Must-know ​

In plain words: io.ReadAll pours the whole reservoir into one bucket that grows as needed. Fine for a config file, dangerous for anything a stranger controls.

Common misunderstanding: "ReadAll is efficient because it is in the standard library." It starts with a 512-byte buffer and grows by append, so a 1 GB input needs at least 1 GB of heap plus growth copies, and the garbage collector has to scan none of it but still account for it. The problem is the shape, not the code.

Definition: "ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF." It moved from io/ioutil in Go 1.16.

1   body, _ := io.ReadAll(r.Body)     // client sends 4 GB with chunked encoding
2   heap grows 512 B -> ... -> 4 GB   // container memory limit 512 MiB
3   OOM kill, exit 137, all in-flight requests lost

Real scenario: an upload endpoint, a webhook receiver, reading a third-party API response that occasionally returns a 200 MB error page, io.ReadAll(resp.Body) in a loop that leaks because the body was never closed.

NeedInstead of ReadAll
Decode JSONjson.NewDecoder(r).Decode(&v) with a limit
Store to disk/S3io.Copy(dst, r)
Hashio.Copy(h, r)
Need bytes, but boundedio.ReadAll(io.LimitReader(r, max+1)) then check len > max
Count linesbufio.Scanner

The adapters snippet's ReadLimited reads limit+1 bytes so that "exactly at the limit" and "over the limit" can be told apart; a plain LimitReader would silently truncate.

io.Writer and short writes Must-know ​

In plain words: a Writer must take the whole slice or explain why not. Unlike Read, there is no "partial success is normal" case.

Common misunderstanding: "I should loop on Write until everything is written, like in C." In Go the contract forbids silent partial writes: "Write must return a non-nil error if it returns n < len(p)". A loop is only needed around non-conforming code; io.Copy reports such a Writer as io.ErrShortWrite.

Definition: Write(p []byte) (n int, err error) writes len(p) bytes, returns how many were written and "any error encountered that caused the write to stop early". "Write must not modify the slice data, even temporarily. Implementations must not retain p." io.StringWriter adds WriteString(s string), and io.WriteString(w, s) uses it when present, otherwise calls Write exactly once.

     io.Copy(ShortWriter{Max: 10}, src)    // src has 100 bytes
1    Read  -> 100 bytes
2    Write -> 10, nil                      // contract violated
3    io.Copy returns 10, io.ErrShortWrite

Real scenario: a full disk (write /data/x: no space left on device), a closed socket (write: broken pipe), a hand-written Writer around a C library that returns partial counts, and bufio.Writer which becomes sticky: "If an error occurs writing to a Writer, no more data will be accepted and all subsequent writes, and Writer.Flush, will return the error."

WriterCan it fail?Notes
*os.FileyesENOSPC, EBADF, permissions
net.Connyesbroken pipe, connection reset, deadline
http.ResponseWriteryesclient went away; first Write sends headers
hash.Hashno"It never returns an error."
bytes.Bufferno (panics on ErrTooLarge)WriteString err "is always nil"
bufio.Writeryes, stickydata reaches the target only on Flush
io.Discardnoalso implements ReaderFrom for speed

io.Closer, ReadCloser and WriteCloser Must-know ​

In plain words: Close gives the resource back (file descriptor, connection, decompressor state) and, for writers, often writes the final bytes. Not closing leaks; not checking Close on a writer can lose data.

Common misunderstanding: "defer f.Close() is all I need." For a reader, yes. For a writer, Close is where a gzip footer, a tar end-of-archive block or the last buffered bytes are written, and where the OS may report a deferred write error. Ignore its error and you ship a corrupt file with a success log line.

Definition: Close() error. "The behavior of Close after the first call is undefined. Specific implementations may document their own behavior." Combined interfaces are plain embeddings: ReadCloser is Reader + Closer, WriteCloser is Writer + Closer, and also ReadWriteCloser, ReadSeekCloser.

1   zw := gzip.NewWriter(f)
2   tw := tar.NewWriter(zw)
3   ... write entries ...
4   tw.Close()   // writes two zero blocks: end of archive
5   zw.Close()   // writes gzip footer: CRC-32 and size
6   f.Close()    // returns any deferred write error
    -- close in reverse order of wrapping; check each error --

Real scenario: a backup job that defers zw.Close() without checking and produces .tar.gz files that tar -tzf rejects; an HTTP client that never closes resp.Body and runs out of file descriptors (socket: too many open files); a test that passes a strings.Reader where a ReadCloser is required and needs io.NopCloser.

TypeClose doesError worth checking?
*os.File (read)release fdrarely
*os.File (write)release fd, may report write erroryes
gzip.Writerflush, write footeryes, always
tar.Writerwrite end-of-archiveyes
bufio.Writerhas no Close; call Flushyes
http.Response.Bodyreturn connection to pool (if drained)no, but always call it
*io.PipeWriterreader gets io.EOFalways returns nil

The archive snippet closes tar then gzip in a deferred function that keeps the first error.

Copying: io.Copy, io.CopyN, io.CopyBuffer Must-know ​

In plain words: io.Copy is the hose. It moves everything from a Reader into a Writer using one 32 KiB buffer, or a faster route if one side offers it.

Common misunderstanding: "io.Copy returns io.EOF at the end." "A successful Copy returns err == nil, not err == EOF. Because Copy is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported." And CopyN is the opposite: if the source ends early it does return io.EOF.

Definition: Copy(dst, src) copies until EOF or error and returns the number of bytes and the first error. If src implements WriterTo it calls src.WriteTo(dst); otherwise if dst implements ReaderFrom it calls dst.ReadFrom(src); otherwise it allocates a 32 KiB buffer (smaller if src is a *LimitedReader with fewer bytes left). CopyN(dst, src, n) copies n bytes; "written == n if and only if err == nil". CopyBuffer "stages through the provided buffer (if one is required)"; "if it has zero length, CopyBuffer panics", and the buffer is unused when a fast path applies.

     io.Copy(dst, src)
1    src is io.WriterTo?   yes -> return src.WriteTo(dst)
2    dst is io.ReaderFrom? yes -> return dst.ReadFrom(src)
3    buf := make([]byte, 32*1024)
4    loop: nr, er := src.Read(buf)
5          if nr > 0: nw, ew := dst.Write(buf[:nr]); nw != nr -> io.ErrShortWrite
6          if er == io.EOF -> return written, nil
io.Copy(dst, src)src implements io.WriterTo?yessrc.WriteTo(dst)nodst implements io.ReaderFrom?yesdst.ReadFrom(src)noloop: Read into 32 KiB buffer,Write it; short write = ErrShortWritekernel fast pathsFile to TCPConn: sendfileTCP/Unix to TCPConn: spliceFile to File: copy_file_rangewrapping src or dst in a non-forwarding adapter hides the fast path

Real scenario: serving a file (io.Copy(w, f)), proxying a socket (io.Copy(upstream, client) in two goroutines), saving an upload to S3, copying exactly Content-Length bytes with CopyN, a hot proxy that allocates 32 KiB per request until CopyBuffer with a sync.Pool buffer fixes it.

go
// Package copying shows how io.Copy chooses its path: WriterTo on the source
// first, then ReaderFrom on the destination, then a 32 KiB buffer loop.
package copying

import (
	"io"
)

// Path records which strategy io.Copy used.
type Path struct{ Used string }

// SpySource is a Reader that also implements io.WriterTo.
type SpySource struct {
	R    io.Reader
	Path *Path
}

func (s SpySource) Read(p []byte) (int, error) { return s.R.Read(p) }

func (s SpySource) WriteTo(w io.Writer) (int64, error) {
	s.Path.Used = "src.WriteTo"
	return io.Copy(struct{ io.Writer }{w}, struct{ io.Reader }{s.R}) // hide fast paths of both sides
}

// SpySink is a Writer that also implements io.ReaderFrom.
type SpySink struct {
	W    io.Writer
	Path *Path
}

func (s SpySink) Write(p []byte) (int, error) { return s.W.Write(p) }

func (s SpySink) ReadFrom(r io.Reader) (int64, error) {
	s.Path.Used = "dst.ReadFrom"
	return io.Copy(struct{ io.Writer }{s.W}, r)
}

// ShortWriter accepts at most Max bytes per call and returns no error:
// a broken Writer that io.Copy reports as io.ErrShortWrite.
type ShortWriter struct{ Max int }

func (s ShortWriter) Write(p []byte) (int, error) {
	if len(p) > s.Max {
		return s.Max, nil // violates "must return a non-nil error if n < len(p)"
	}
	return len(p), nil
}

// CopyWithPool copies through a caller-owned buffer so hot paths do not
// allocate 32 KiB per call. The buffer is ignored if a fast path applies.
func CopyWithPool(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
	return io.CopyBuffer(dst, src, buf)
}

// CopyExactly copies exactly n bytes or fails; useful when a header announced
// the size (Content-Length, a tar entry, a frame length).
func CopyExactly(dst io.Writer, src io.Reader, n int64) error {
	written, err := io.CopyN(dst, src, n)
	if err == io.EOF && written < n {
		return io.ErrUnexpectedEOF
	}
	return err
}
$ go test -v ./copying
    copying_test.go:40: copied 10 bytes, err: short write
    copying_test.go:54: recovered: empty buffer in CopyBuffer
ok  	academy/io-readers-writers/copying

Fast paths and zero-copy: WriterTo, ReaderFrom, sendfile, splice Important ​

In plain words: when both ends of the hose are in the kernel (a file and a socket), Go can ask the kernel to move the bytes directly, so they never enter your process. You get this for free from io.Copy, as long as you do not hide the concrete types behind wrappers.

Common misunderstanding: "Zero-copy needs special APIs." In Go it needs the opposite: plain io.Copy with the real *os.File and *net.TCPConn. Wrapping the file in a bufio.Reader, a counting reader or struct{ io.Reader } removes the WriterTo method and drops you back to the 32 KiB loop.

Definition: WriterTo ("WriteTo writes data to w until there's no more data to write") and ReaderFrom ("ReadFrom reads data from r until EOF or error") are optional interfaces that io.Copy checks with type assertions. In the Go 1.25 source, *net.TCPConn.ReadFrom tries spliceFrom (Linux splice(2) from a TCP or stream-oriented Unix socket), then sendFile (from a file, built for Linux, macOS, FreeBSD, DragonFly, Solaris, Windows), then a generic copy. TCPConn.WriteTo splices to a Unix socket. *os.File.ReadFrom on Linux tries copy_file_range(2) and splice(2) ("Neither copy_file_range(2) nor splice(2) supports destinations opened with O_APPEND"). Go 1.22 added File.WriteTo (sendfile to net.UnixConn) and TCPConn.WriteTo (splice).

     io.Copy(conn *net.TCPConn, f *os.File)       Linux
1    f is WriterTo (Go 1.22+) -> f.WriteTo(conn)
2    File.WriteTo: dest not a Unix socket -> generic path, hides its own WriteTo
3    conn is ReaderFrom -> conn.ReadFrom(file)
4    spliceFrom: src not a socket -> not handled
5    sendFile(fd, file) -> sendfile(2): disk page cache -> socket, no user copy

Real scenario: a static file or download server, a video segment server, a TCP proxy between two sockets, cp-like tools; on Linux http.ServeContent and http.FileServer benefit because ResponseWriter forwards ReadFrom to the connection for plain HTTP/1.x bodies (TLS cannot use sendfile because encryption happens in user space).

Source to destinationMechanism (Linux)Lost when
*os.File to *net.TCPConnsendfile(2)file wrapped, TLS in between
TCP/Unix socket to *net.TCPConnsplice(2)either side wrapped
*net.TCPConn to *net.UnixConnsplice(2) (Go 1.22)wrapped
*os.File to *net.UnixConnsendfile(2) (Go 1.22)wrapped
*os.File to *os.Filecopy_file_range(2), else splicedestination O_APPEND
bytes.Buffer, strings.Reader to anythingWriteTo: one Write of the whole contentwrapped
anything to io.DiscardReadFrom with pooled buffer

A wrapper that must exist (for metrics) can keep the fast path by implementing ReadFrom/WriteTo itself and delegating. The copying snippet proves the order: when both sides implement a fast path, the source's WriteTo wins. For the socket side of the story, see Ports, Sockets & Connections.

io.Pipe Important ​

In plain words: a pipe connects code that wants to write (an encoder) with code that wants to read (an HTTP upload, an S3 client) without a buffer in between. Each write waits until the reader has taken the bytes.

Common misunderstanding: "A pipe is like a buffered channel of bytes." It has no buffer at all, so writer and reader must run in different goroutines; writing and reading in the same goroutine deadlocks (fatal error: all goroutines are asleep - deadlock!).

Definition: Pipe() "creates a synchronous in-memory pipe ... each Write to the PipeWriter blocks until it has satisfied one or more Reads from the PipeReader that fully consume the written data. The data is copied directly from the Write to the corresponding Read (or Reads); there is no internal buffering." It is safe to call Read and Write in parallel. PipeWriter.Close makes reads return io.EOF; PipeWriter.CloseWithError(err) makes them return err; PipeReader.Close makes writes return io.ErrClosedPipe; CloseWithError "never overwrites the previous error if it exists and always returns nil".

     producer goroutine                    consumer (http.Client.Do with pr as Body)
1    enc.Encode(e1) -> pw.Write blocks
2                                          transport reads 4 KiB from pr
3    Write returns; enc.Encode(e2) ...
4    database cursor fails
5    pw.CloseWithError(err)
6                                          pr.Read returns err; upload aborted
     -- or the consumer gives up first --
5'                                         pr.Close()
6'   next pw.Write -> io: read/write on closed pipe; goroutine exits
producer goroutinejson.Encoderover gzip.Writerover pw (PipeWriter)Write blocks hereio.Pipeno buffer: hand-offconsumerpr (PipeReader) ashttp request Body,S3 upload, io.Copyits speed sets the pacebackpressure: Write returns only after Read took the bytespw.CloseWithError(err): reader gets errpw.Close(): reader gets io.EOFpr.Close(): next Write returnsio: read/write on closed pipe

Real scenario: streaming a gzip-compressed JSON export as an HTTP request body; uploading a generated CSV to S3 with a client that wants an io.Reader; feeding exec.Cmd.Stdin from an encoder; connecting tar.Writer output to a gzip-reading consumer in tests.

go
// Package pipe connects a producer that wants an io.Writer to a consumer that
// wants an io.Reader, without buffering the whole payload, using io.Pipe.
package pipe

import (
	"compress/gzip"
	"encoding/json"
	"io"
)

// Event is one record in the stream.
type Event struct {
	ID   int    `json:"id"`
	Kind string `json:"kind"`
}

// GzipJSONStream returns a Reader that yields gzip-compressed JSON lines for
// events. The encoder runs in its own goroutine and writes into the pipe;
// every Write blocks until the consumer has read it (backpressure).
func GzipJSONStream(events []Event) io.ReadCloser {
	pr, pw := io.Pipe()
	go func() {
		zw := gzip.NewWriter(pw)
		enc := json.NewEncoder(zw)
		for _, e := range events {
			if err := enc.Encode(e); err != nil {
				pw.CloseWithError(err) // the reader sees this error, not EOF
				return
			}
		}
		if err := zw.Close(); err != nil { // flush the gzip footer
			pw.CloseWithError(err)
			return
		}
		pw.Close() // reader sees io.EOF
	}()
	return pr
}

// ReadEvents decodes what GzipJSONStream produced.
func ReadEvents(r io.Reader) ([]Event, error) {
	zr, err := gzip.NewReader(r)
	if err != nil {
		return nil, err
	}
	defer zr.Close()
	dec := json.NewDecoder(zr)
	var out []Event
	for {
		var e Event
		if err := dec.Decode(&e); err == io.EOF {
			return out, nil
		} else if err != nil {
			return out, err
		}
		out = append(out, e)
	}
}

// FailingProducer shows CloseWithError: the consumer gets the producer's error.
func FailingProducer(cause error) io.Reader {
	pr, pw := io.Pipe()
	go func() {
		_, _ = io.WriteString(pw, "partial ")
		pw.CloseWithError(cause)
	}()
	return pr
}

The tests run with -race, check that CloseWithError reaches the reader with the producer's error and the partial data, that writing after pr.Close() returns exactly io.ErrClosedPipe, and that a consumer that stops after 10 bytes and closes unblocks the producer goroutine instead of leaking it.

The adapter set: MultiReader, MultiWriter, TeeReader, LimitReader, NopCloser, Discard Must-know ​

In plain words: small fittings from the io package that each change one thing about a stream: join several (MultiReader), duplicate (MultiWriter), copy what passes by (TeeReader), stop after n bytes (LimitReader), add a fake Close (NopCloser), or throw away (Discard).

Common misunderstanding: "MultiWriter writes to all writers even if one fails." It stops: "If a listed writer returns an error, that overall write operation stops and returns the error; it does not continue down the list." And TeeReader has "no internal buffering - the write must complete before the read completes", so a slow tee target slows the reader.

Definition:

AdapterDoc wording (Go 1.25)Typical use
io.MultiReader(r1, r2, ...)"the logical concatenation of the provided input readers. They're read sequentially."header + body + trailer without copying
io.MultiWriter(w1, w2, ...)"duplicates its writes to all the provided writers, similar to the Unix tee(1) command"store + hash + count in one pass
io.TeeReader(r, w)"writes to w what it reads from r"; write errors become read errorshash an upload while a decoder reads it
io.LimitReader(r, n)"stops with EOF after n bytes"; a *LimitedReader whose N counts downcap untrusted input
io.NopCloser(r)"a ReadCloser with a no-op Close method"; forwards WriterTotests, http.Request.Body
io.Discard"a Writer on which all Write calls succeed without doing anything"drain a body, benchmarks
io.NewSectionReader(ra, off, n)Read, Seek, ReadAt on a sectionone part of a file
io.NewOffsetWriter(wa, off)maps writes to offset offparallel chunk download into one file
1   r, done := VerifyWhileReading(upload)     // TeeReader(upload, sha256)
2   json.NewDecoder(r).Decode(&manifest)      // decoder pulls bytes
3   every pulled byte also goes into the hash
4   io.Copy(io.Discard, r)                    // drain the rest so the hash covers all
5   done() == expected digest ?

Real scenario: content-addressed storage (hash while writing), audit copies of a request body to a log with TeeReader (bounded with LimitReader), joining a CSV header to a data stream, tests that need a ReadCloser.

go
// Package adapters builds small io.Writer and io.Reader adapters and composes
// the standard ones: MultiWriter, TeeReader, LimitReader, SectionReader,
// MultiReader, NopCloser and Discard.
package adapters

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"strings"
)

// CountingWriter counts bytes written through it to W.
type CountingWriter struct {
	W io.Writer
	N int64
}

func (c *CountingWriter) Write(p []byte) (int, error) {
	n, err := c.W.Write(p)
	c.N += int64(n) // count what was really written, not len(p)
	return n, err
}

// StoreWithChecksum copies src to dst and returns the SHA-256 and byte count
// computed in the same pass: one read, three consumers.
func StoreWithChecksum(dst io.Writer, src io.Reader) (sum string, n int64, err error) {
	h := sha256.New() // hash.Hash is an io.Writer whose Write never fails
	cw := &CountingWriter{W: dst}
	if _, err = io.Copy(io.MultiWriter(cw, h), src); err != nil {
		return "", cw.N, err
	}
	return hex.EncodeToString(h.Sum(nil)), cw.N, nil
}

// VerifyWhileReading returns a Reader that hashes everything the caller
// reads, plus a function that reports the digest once reading has finished.
func VerifyWhileReading(src io.Reader) (io.Reader, func() string) {
	h := sha256.New()
	return io.TeeReader(src, h), func() string { return hex.EncodeToString(h.Sum(nil)) }
}

// ErrTooLarge is returned by ReadLimited when the input exceeds the limit.
var ErrTooLarge = fmt.Errorf("adapters: input larger than limit")

// ReadLimited reads at most limit bytes and reports ErrTooLarge instead of
// silently truncating: read limit+1 and check.
func ReadLimited(r io.Reader, limit int64) ([]byte, error) {
	b, err := io.ReadAll(io.LimitReader(r, limit+1))
	if err != nil {
		return nil, err
	}
	if int64(len(b)) > limit {
		return nil, ErrTooLarge
	}
	return b, nil
}

// Section returns a Reader over bytes [off, off+n) of ra, for example one
// part of a multipart upload or one record of a fixed-width file.
func Section(ra io.ReaderAt, off, n int64) *io.SectionReader {
	return io.NewSectionReader(ra, off, n)
}

// WithPreamble prepends a header and appends a trailer without copying the body.
func WithPreamble(header string, body io.Reader, trailer string) io.Reader {
	return io.MultiReader(strings.NewReader(header), body, strings.NewReader(trailer))
}

// AsReadCloser adapts a plain Reader to an API that demands a ReadCloser
// (http.Request.Body in tests, for example).
func AsReadCloser(r io.Reader) io.ReadCloser { return io.NopCloser(r) }

// Drain consumes and discards the rest of r and returns how many bytes it threw away.
func Drain(r io.Reader) (int64, error) { return io.Copy(io.Discard, r) }

Seeker and random access: Seek, whence, ReadSeeker, SectionReader Important ​

In plain words: most streams only go forward. Some (files, in-memory readers) let you move the cursor: to an absolute position, relative to where you are, or relative to the end.

Common misunderstanding: "Every Reader can Seek." Sockets, pipes, HTTP bodies and gzip streams cannot; asking for io.ReadSeeker in an API excludes them. Ask for the smallest interface you need; if you need random access, io.ReaderAt is often better because "Clients of ReadAt can execute parallel ReadAt calls on the same input source".

Definition: Seek(offset int64, whence int) (int64, error) with io.SeekStart = 0 ("relative to the origin of the file"), io.SeekCurrent = 1, io.SeekEnd = 2 ("for example, offset = -2 specifies the penultimate byte"). It returns the new offset from the start. "Seeking to an offset before the start of the file is an error." ReadAt is stricter than Read: when it returns n < len(p) it returns a non-nil error, and it "should not affect nor be affected by the underlying seek offset".

     s := io.NewSectionReader(ra, 6, 16)     // bytes 6..21 of the source
1    s.Seek(8, io.SeekStart)    -> 8
2    io.ReadFull(s, rec[:8])    -> "record-2"
3    s.Seek(-8, io.SeekEnd)     -> 8
4    s.Seek(-8, io.SeekCurrent) -> 0
5    s.Seek(-1, io.SeekStart)   -> error "Seek: invalid offset"

Real scenario: http.ServeContent needs an io.ReadSeeker to answer Range requests and find the size; reading a ZIP central directory from the end (archive/zip.NewReader takes a ReaderAt and size); rewinding a request body for a retry (Seek(0, io.SeekStart)); parallel range downloads writing with OffsetWriter.

TypeSeekerReaderAtNotes
*os.FileyesyesSeek on a pipe/terminal fails
*bytes.Reader, *strings.Readeryesyesalso WriterTo
*bytes.Buffernonoconsumed as read
*io.SectionReaderyesyeswindow over a ReaderAt
net.Conn, http.Request.Body, gzip.Readernonoforward only

bufio: buffered readers, writers and scanners Must-know ​

In plain words: bufio puts a bucket (4 KiB by default) between you and a slow source or sink, so a thousand tiny reads or writes become a few big system calls, and you get line and token helpers.

Common misunderstanding: "bufio.Writer writes as I go." It writes when the buffer is full or when you call Flush; forget Flush and up to 4096 bytes never arrive, without any error. And bufio.Scanner has a token limit: lines longer than 64 KiB fail with bufio.Scanner: token too long unless you call Buffer.

Definition: bufio.NewReader(r) and bufio.NewWriter(w) use defaultBufSize = 4096; NewReaderSize/NewWriterSize choose another size and return the argument itself if it is already a buffered type that is large enough. Writer: "After all data has been written, the client should call the Writer.Flush method". bufio.Scanner splits input with a SplitFunc (ScanLines default, ScanWords, ScanRunes, ScanBytes); MaxScanTokenSize = 64 * 1024; Scanner.Buffer(buf, max) raises the limit. bufio.Reader implements io.ByteReader, io.RuneScanner, ReadString, ReadLine, Peek.

1   bw := bufio.NewWriter(f)
2   fmt.Fprintf(bw, "%-10s %6d\n", "orders", 42)   // in buffer, 18 bytes
3   fmt.Fprintf(bw, ...)                            // in buffer
4   return nil                                       // BUG: file is empty
4'  return bw.Flush()                                // bytes reach f; errors reported

Real scenario: writing a CSV report line by line, parsing a log with Scanner, reading a line protocol (Redis RESP, SMTP) with ReadString('\n'), Peek to sniff a file type before choosing a decoder, a JSON-lines file with a 200 KB line breaking a naive scanner.

ToolDefaultKnobError
bufio.Reader4096 BNewReaderSizebufio: buffer full (ErrBufferFull) from ReadSlice/Peek
bufio.Writer4096 BNewWriterSizesticky first write error
bufio.Scanner64 KiB max tokenBuffer(buf, max)bufio.Scanner: token too long
ReadString('\n')unboundedreturns data plus io.EOF if no final newline
ReadLinebuffer sizelow-level; prefer ReadString or Scanner

The chunked snippet's CountLines shows the token limit and the fix, and WriteReport writes with fmt.Fprintf through a bufio.Writer and returns Flush's error. File-specific bufio patterns are in Files, Directories, Paths, Temp Files, bufio & embed.

In-memory readers and writers: bytes.Buffer, strings.Reader, bytes.Reader Must-know ​

In plain words: three ways to treat memory as a stream: bytes.Buffer is a growable bucket you write into and read out of (reading consumes); strings.Reader and bytes.Reader are read-only views over existing data that can seek.

Common misunderstanding: "bytes.Buffer and bytes.Reader are the same." Reading a Buffer removes the data; it cannot seek or be re-read. A bytes.Reader never changes the slice and can rewind, so it is the right type for a retryable request body. And strings.NewReader(s) does not copy s.

Definition: bytes.Buffer implements Reader, Writer, ByteReader, RuneReader, StringWriter, ReaderFrom and WriterTo; its zero value is ready to use; growth beyond memory panics with bytes.Buffer: too large (ErrTooLarge). strings.Reader implements Reader, ReaderAt, Seeker, WriterTo, ByteScanner, RuneScanner. bytes.Reader is the same over []byte. strings.Builder is write-only and builds a string without a final copy.

1   var b bytes.Buffer
2   b.WriteString("hello ")        // len 6
3   fmt.Fprintf(&b, "%d", 42)      // len 8 (Buffer is an io.Writer)
4   io.Copy(os.Stdout, &b)         // WriterTo: one Write of 8 bytes; b now empty
5   r := bytes.NewReader(data)
6   io.Copy(dst, r); r.Seek(0, io.SeekStart); io.Copy(dst2, r)   // re-readable

Real scenario: building a request body in a test, capturing log output (log.New(&buf, "", 0)), http.NewRequest with a bytes.Reader (the client sets GetBody so redirects can replay it), a parser that accepts io.Reader and is fed a strings.NewReader in tests.

TypeReadWriteSeekRe-readUse for
bytes.Bufferconsumesyesnonoassembling output, FIFO
bytes.Readeryesnoyesyesreplayable bodies, ReaderAt
strings.Readeryesnoyesyesfeeding strings to Reader APIs
strings.Buildernoyesnon/abuilding strings

Writer adapters: counting writer, hashing writer, StringWriter, Fprintf Important ​

In plain words: because a Writer is one method, you can write a tiny type that sits in the pipe and does something with every byte: count it, hash it, log it, throttle it.

Common misunderstanding: "I need to hash the file in a second pass after saving it." io.MultiWriter(dst, h) hashes during the copy; the hash is itself a Writer. Also, a counting writer must count the n the inner writer returned, not len(p), or a failed write is over-counted.

Definition: a counting writer wraps W io.Writer, calls it, adds n to a counter and returns n, err unchanged. A hashing writer is any hash.Hash (sha256.New()), whose Write "never returns an error". fmt.Fprintf(w, format, args...) formats into any io.Writer; io.WriteString uses StringWriter to avoid a []byte conversion when available.

1   h := sha256.New()
2   cw := &CountingWriter{W: s3upload}
3   io.Copy(io.MultiWriter(cw, h), upload)
4   -> one read of each 32 KiB chunk; written to S3, counted, hashed
5   store (key, cw.N, hex(h.Sum(nil))) in the database

Real scenario: content-addressed uploads (sha256 as the object key), metrics on bytes served per tenant, Content-Length known only after compression, ETag generation, progress bars on large downloads.

AdapterImplementsNote
Counting writerWritecount n, not len(p)
Hashing writerhash.Hash is a Writerh.Sum(nil) at the end
io.MultiWriter(dst, h)fan-outstops at the first error
Rate-limited writerWrite with rate.Limiter.WaitNsee rate limiting
Prefix/log writeriotest.NewWriteLogger(prefix, w)debugging
fmt.Fprintfany io.Writerreturns bytes written and error

The test TestStoreWithChecksum checks bytes, count and digest from a single pass; algorithm choice is in Hashing & Crypto and Checksums & Hashing.

A custom Reader: a small state machine Important ​

In plain words: to be a Reader you only need Read. A transforming Reader reads from another one and changes the bytes; a generating Reader produces bytes from some state (a cursor, a counter) on demand, keeping only the current piece in memory.

Common misunderstanding: "My Read must produce exactly one record per call." The caller's buffer decides the size: a row may span several calls, and one call may carry several rows. Keep the unread tail of the current item in a field (the state) and copy as much as fits.

Definition: a correct Read copies at most len(p) bytes, returns n > 0 whenever it has data, returns 0, io.EOF (or n, io.EOF) only at the end, never returns 0, nil for a non-empty p, passes errors of a wrapped Reader through unchanged (so == io.EOF still works) and does not keep p.

     RowSource state: pending = "2,user-2\n", next = 2
1    Read(p[:4])  -> copies "2,us", pending = "er-2\n"          return 4, nil
2    Read(p[:64]) -> copies "er-2\n"; fill() -> pending row 3;
                     copies "3,user-3\n"; fill() -> no more rows  return 14, nil
3    Read(p)      -> nothing pending, fill() false               return 0, io.EOF

Real scenario: streaming a database export as CSV without building it in memory, generating synthetic load-test payloads, an ROT13/Base64/line-ending transformer, decrypting a stream chunk by chunk, wrapping a cursor-based API (S3 list, DB rows) as a byte stream for io.Copy to an HTTP response.

go
// Package customreader implements Readers by hand: a wrapping transformer
// (rot13) and a generating state machine (CSV rows produced on demand).
package customreader

import (
	"fmt"
	"io"
	"iter"
	"strconv"
)

// Rot13 wraps another Reader and transforms bytes in place.
type Rot13 struct{ R io.Reader }

func (r Rot13) Read(p []byte) (int, error) {
	n, err := r.R.Read(p)
	for i := range p[:n] { // transform only the n bytes that were read
		p[i] = rot13(p[i])
	}
	return n, err // pass the error through unchanged (io.EOF must stay ==)
}

func rot13(b byte) byte {
	switch {
	case b >= 'a' && b <= 'z':
		return 'a' + (b-'a'+13)%26
	case b >= 'A' && b <= 'Z':
		return 'A' + (b-'A'+13)%26
	}
	return b
}

// RowSource produces "id,name\n" rows for ids 1..Total without building the
// whole document in memory. It is a small state machine:
// pending holds the unread tail of the current row; next is the next id.
type RowSource struct {
	Total   int
	next    int
	pending []byte
	started bool
}

// NewRowSource returns a Reader that streams a CSV with a header line.
func NewRowSource(total int) *RowSource { return &RowSource{Total: total} }

func (s *RowSource) Read(p []byte) (int, error) {
	if len(p) == 0 {
		return 0, nil
	}
	n := 0
	for n < len(p) {
		if len(s.pending) == 0 {
			if !s.fill() {
				break // no more rows
			}
		}
		c := copy(p[n:], s.pending) // a row may span several Read calls
		s.pending = s.pending[c:]
		n += c
	}
	if n == 0 {
		return 0, io.EOF // only report EOF when nothing was produced
	}
	return n, nil
}

// fill prepares the next row; it returns false when the stream is finished.
func (s *RowSource) fill() bool {
	if !s.started {
		s.started = true
		s.pending = []byte("id,name\n")
		return true
	}
	if s.next >= s.Total {
		return false
	}
	s.next++
	s.pending = fmt.Appendf(s.pending[:0], "%d,user-%s\n", s.next, strconv.Itoa(s.next))
	return true
}

// Rows is the iterator (Go 1.23 range-over-func) version of the same data.
// An iterator yields typed values to one consumer; a Reader yields bytes that
// any io function (Copy, gzip, http) can consume.
func Rows(total int) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		for id := 1; id <= total; id++ {
			if !yield(id, "user-"+strconv.Itoa(id)) {
				return
			}
		}
	}
}

TestRowSourceIsLazy streams a million rows (18,777,800 bytes) through io.Copy to io.Discard with constant memory, and both Readers pass iotest.TestReader.

Deadlines and context: cancelling a blocked Read Important ​

In plain words: Read has no ctx parameter. To stop a read that waits forever you either set a deadline on the thing being read (sockets support this), close it from another goroutine, or check a context between reads.

Common misunderstanding: "Wrapping a Reader with a context check makes it cancellable." It stops the next Read, not one that is already blocked inside the kernel. Only a deadline (or Close) interrupts a blocked socket read.

Definition: net.Conn has SetDeadline, SetReadDeadline, SetWriteDeadline; a read past the deadline fails with an error for which errors.Is(err, os.ErrDeadlineExceeded) is true and net.Error.Timeout() returns true; its text ends in i/o timeout. os.File supports deadlines for pipes and other pollable descriptors. context.AfterFunc(ctx, f) (Go 1.21) runs f when ctx is done, which can move the deadline into the past. HTTP request bodies are cancelled through the request's context and server timeouts (ReadTimeout, http.ResponseController.SetReadDeadline).

     goroutine A                                   ctx (timeout 30 ms)
1    stop := context.AfterFunc(ctx, setPastDeadline)
2    conn.Read(buf)  -- blocks, peer silent
3                                                  30 ms: ctx done, AfterFunc runs
4                                                  conn.SetReadDeadline(time.Unix(1, 0))
5    Read returns "read pipe: i/o timeout"
6    ctx.Err() == context.DeadlineExceeded -> report "context deadline exceeded"

Real scenario: a TCP client to a payment gateway that must not hang a worker forever, a slowloris client trickling a request body, an export job cancelled by the user while io.Copy is streaming, an SSH or database protocol read with a per-message deadline.

SourceInterrupt a blocked Read withError
net.Conn (TCP, Unix, net.Pipe)SetReadDeadline, Closei/o timeout / use of closed network connection
*os.File pipe or FIFOSetReadDeadline, Closei/o timeout / file already closed
regular *os.Filenot interruptible (disk reads finish)
http.Request.Body (server)server ReadTimeout, ResponseControlleri/o timeout
http.Response.Body (client)request ctx, Client.Timeoutcontext deadline exceeded
io.PipeReaderCloseWithError on either sideyour error
any Reader between readsctx.Err() check wrappercontext canceled
go
// Package deadline adds cancellation to reads. The io interfaces have no
// context parameter, so there are two tools: deadlines on things that support
// them (net.Conn, os.File pipes) and wrappers that check a context between reads.
package deadline

import (
	"context"
	"io"
	"net"
	"time"
)

// ctxReader returns ctx.Err() before each Read once ctx is done. It cannot
// interrupt a Read that is already blocked; it stops the next one.
type ctxReader struct {
	ctx context.Context
	r   io.Reader
}

// Reader wraps r so that a long copy loop stops soon after ctx is cancelled.
func Reader(ctx context.Context, r io.Reader) io.Reader { return &ctxReader{ctx: ctx, r: r} }

func (c *ctxReader) Read(p []byte) (int, error) {
	if err := c.ctx.Err(); err != nil {
		return 0, err
	}
	return c.r.Read(p)
}

// ReadWithDeadline reads into p from conn but gives up at the deadline.
// The error then satisfies errors.Is(err, os.ErrDeadlineExceeded).
func ReadWithDeadline(conn net.Conn, p []byte, d time.Duration) (int, error) {
	if err := conn.SetReadDeadline(time.Now().Add(d)); err != nil {
		return 0, err
	}
	defer conn.SetReadDeadline(time.Time{}) // clear for the next caller
	return conn.Read(p)
}

// CancelOnDone interrupts a blocked Read on conn when ctx ends, by moving the
// deadline into the past. It returns a stop function that must be called.
func CancelOnDone(ctx context.Context, conn net.Conn) (stop func() bool) {
	return context.AfterFunc(ctx, func() {
		_ = conn.SetReadDeadline(time.Unix(1, 0))
	})
}

Context semantics are covered in context; this page only shows how they reach I/O.

Testing readers with testing/iotest Good to know ​

In plain words: iotest gives you misbehaving-but-legal Readers so your code meets every allowed shape of Read in tests, not first in production.

Common misunderstanding: "My parser works with strings.Reader, so it works." strings.Reader always fills the buffer and returns 0, io.EOF separately; a network Reader returns odd sizes and may return data with io.EOF. Test against OneByteReader, HalfReader and DataErrReader.

Definition:

FunctionBehaviour
iotest.OneByteReader(r)each Read returns one byte
iotest.HalfReader(r)each Read returns half the requested bytes
iotest.DataErrReader(r)returns the final data together with the error (typically EOF)
iotest.TimeoutReader(r)second Read returns iotest.ErrTimeout (text timeout) with no data
iotest.ErrReader(err)every Read returns 0, err
iotest.TruncateWriter(w, n)writes to w but stops silently after n bytes
iotest.NewReadLogger, NewWriteLoggerlog every call with a prefix
iotest.TestReader(r, content)reads with many sizes until EOF; checks ReadAt/Seek if implemented
1   r := iotest.TimeoutReader(strings.NewReader(2000 x "x"))
2   CountBytes(r): Read 512 bytes -> ok
3   Read -> 0, iotest.ErrTimeout
4   CountBytes returns 512, timeout   // error surfaced, partial count kept

Real scenario: testing a frame decoder against one-byte reads, a checksum function against data-with-EOF, a retry wrapper against ErrReader, and proving a custom Reader correct with TestReader before using it in production. Test structure itself is in Testing & Benchmarking.

Readers and iterators Good to know ​

In plain words: a Reader streams bytes to anyone; an iterator (iter.Seq, Go 1.23) streams typed values to one for range loop. Use a Reader at system boundaries (files, network, compression), an iterator inside your program once bytes have been parsed into records.

Common misunderstanding: "Iterators replace io.Reader." They do not compose with io.Copy, gzip, HTTP or hashes; and a Reader of records would force every consumer to re-parse. They sit on different sides of the decoder.

Definition: an iter.Seq2[K, V] is func(yield func(K, V) bool); the producer pushes values and stops when yield returns false. A Reader is pulled by the consumer with a buffer it owns. The range-functions blog post calls these the push and pull styles.

1   for i, line := range Lines(file) {   // bufio.Scanner inside the iterator
2       if i == 2 { break }               // yield returns false -> iterator returns
3   }
4   the file Reader underneath was pulled only as far as needed

Real scenario: Lines(r) over a log file, Rows(n) producing records for an in-process pipeline, then encoding those records back into a Reader for an HTTP response. For channel-based pipelines see Worker Pools, Pipelines, Fan-Out/Fan-In.

io.Readeriter.Seq
Unitbytestyped values
Who drivesconsumer pulls with its bufferproducer pushes into the loop body
Composes withio.Copy, gzip, tar, net, hashfor range, slices.Collect, maps
Errors(n, err) per callmust be a value in the sequence or a side channel
Early stopstop calling Read, Closebreak

Mechanics ​

Exact messages and what they mean Must-know ​

MessageWhere it comes fromMeaning and fix
EOFio.EOFnormal end; handle as success in loops
unexpected EOFio.ErrUnexpectedEOF, gzip, json, tarinput cut in the middle; treat as corrupt/truncated
short writeio.ErrShortWritea Writer broke the contract; fix the Writer
short bufferio.ErrShortBufferReadAtLeast with min > len(buf)
io: read/write on closed pipeio.ErrClosedPipethe other end of the pipe was closed
multiple Read calls return no data or errorio.ErrNoProgress (bufio)a Reader keeps returning 0, nil
empty buffer in CopyBufferpanic in io.CopyBufferpassed make([]byte, 0)
Seek: invalid offsetSectionReader.Seeknegative resulting position
http: request body too large*http.MaxBytesErrorbody over MaxBytesReader limit; answer 413
bufio.Scanner: token too longbufio.ErrTooLongline over the Scanner max; call Buffer
bufio: buffer fullbufio.ErrBufferFullReadSlice/Peek longer than the buffer
bytes.Buffer: too largepanic bytes.ErrTooLargebuffer could not grow; stream instead
gzip: invalid headergzip.ErrHeaderinput is not gzip (often already decompressed)
read pipe: i/o timeout / read tcp ...: i/o timeoutos.ErrDeadlineExceededdeadline passed
context deadline exceededcontext.DeadlineExceededthe request context ended
write: broken pipesyscall.EPIPEpeer closed; stop writing
fatal error: all goroutines are asleep - deadlock!runtimeio.Pipe read and written in one goroutine

The texts above that the snippet tests print were captured on Go 1.27.4 (module go 1.24): unexpected EOF, short write, empty buffer in CopyBuffer, Seek: invalid offset, io: read/write on closed pipe, gzip: invalid header, bufio.Scanner: token too long, read pipe: i/o timeout, context deadline exceeded.

Sizes, defaults and knobs Important ​

ItemValue (Go 1.25 source)Change with
io.Copy buffer32 KiB (32 * 1024), smaller for a LimitedReaderio.CopyBuffer
io.ReadAll initial capacity512 bytes, grows by appendread into a pre-sized buffer if size is known
bufio default size4096 bytesNewReaderSize, NewWriterSize
bufio.MaxScanTokenSize64 KiBScanner.Buffer(buf, max)
bytes.Buffer first allocation64 bytes (smallBufferSize)Grow(n)
http.MaxBytesReaderyour n; negative treated as 0per route
json.Decoderown buffering; may read beyond the valueDecoder.Buffered() returns the rest
php://temp (comparison)memory until 2 MB, then a temp file/maxmemory:NN

How a composition really runs Good to know ​

When you write io.Copy(dst, gz) where gz := gzip.NewReader(bufio.NewReader(f)), nothing happens until io.Copy calls gz.Read(buf). The gzip reader then asks the bufio.Reader for compressed bytes, which asks the file for 4 KiB, and so on down. Each layer pulls only what it needs to fill the request above it. On the write side the push goes the other way: tw.Write pushes into zw.Write, which compresses and pushes into the file. Memory in flight is the sum of the layers' buffers (a few tens of KiB for gzip's window plus the copy buffer), not the file size. This is the property that the Composition pipeline diagram below shows.

Solving the classic problems ​

Problem: write and read a tar.gz without loading it ​

SolutionHowAdvantageCost / limit
Layered writerstar.NewWriter(gzip.NewWriter(f)), close tar then gzip then fileconstant memory, any destinationclose order and errors matter
Layered readerstar.NewReader(gzip.NewReader(f)), tr.Next() per entrystream entries; tr is the entry Readermust validate names and sizes
os.ReadFile + bytes.Readerwhole file in memorysimplememory = archive size
Read side (pull): each box wraps the one on its left*os.Filebackup.tar.gzgzip.Readerinflatetar.Readerone entryLimitReadercap untrusted sizeTeeReadercopy to hashsha256 hashio.Copy(dst, src) 32 KiB at a timeWrite side (push)MultiWriterfan out each Writestoragefile, S3, HTTPcounting writerbytes for metricsmemory used: a few buffers, independent of file size
go
// Package archive composes Writers and Readers: file -> gzip -> tar, and back.
// Each layer only knows io.Writer or io.Reader, so the same code writes to a
// file, an HTTP response or an S3 upload stream.
package archive

import (
	"archive/tar"
	"compress/gzip"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"path"
	"time"
)

// File is one entry to archive.
type File struct {
	Name string
	Body io.Reader
	Size int64
}

// WriteTarGz writes files into w as a .tar.gz. Close order matters:
// tar first (writes the end-of-archive blocks), then gzip (writes the footer).
func WriteTarGz(w io.Writer, files []File) (err error) {
	zw := gzip.NewWriter(w)
	tw := tar.NewWriter(zw)
	defer func() {
		if cerr := tw.Close(); err == nil {
			err = cerr
		}
		if cerr := zw.Close(); err == nil {
			err = cerr
		}
	}()
	for _, f := range files {
		hdr := &tar.Header{
			Name:    f.Name,
			Mode:    0o644,
			Size:    f.Size,
			ModTime: time.Unix(0, 0),
		}
		if err := tw.WriteHeader(hdr); err != nil {
			return err
		}
		if _, err := io.CopyN(tw, f.Body, f.Size); err != nil {
			return fmt.Errorf("archive %s: %w", f.Name, err)
		}
	}
	return nil
}

// ErrUnsafePath is returned for entries that would escape the target directory.
var ErrUnsafePath = errors.New("archive: unsafe entry path")

// Walk streams a .tar.gz and calls fn for each regular file with a Reader
// limited to that entry. Nothing is buffered beyond gzip's window.
func Walk(r io.Reader, maxEntry int64, fn func(name string, body io.Reader) error) error {
	zr, err := gzip.NewReader(r)
	if err != nil {
		return err
	}
	defer zr.Close()
	tr := tar.NewReader(zr)
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		if !fs.ValidPath(hdr.Name) || path.IsAbs(hdr.Name) {
			return fmt.Errorf("%w: %q", ErrUnsafePath, hdr.Name)
		}
		if hdr.Typeflag != tar.TypeReg {
			continue
		}
		if hdr.Size > maxEntry {
			return fmt.Errorf("archive: %s is %d bytes, limit %d", hdr.Name, hdr.Size, maxEntry)
		}
		// tr itself is the Reader for the current entry; it returns EOF at its end.
		if err := fn(hdr.Name, tr); err != nil {
			return err
		}
	}
}

Walk rejects ../etc/passwd-style names with fs.ValidPath (path traversal, often called "zip slip"), skips non-regular entries and enforces a per-entry size limit. The tests cover a round trip through a real temp file, a size mismatch (archive short: EOF from CopyN), a non-gzip input (gzip: invalid header) and a truncated archive (unexpected EOF). The same WriteTarGz can write to an http.ResponseWriter to stream a download, or to an io.PipeWriter to feed an upload. Algorithms behind gzip are in Compression.

Problem: decode JSON from a network stream ​

SolutionHowAdvantageCost / limit
json.NewDecoder(r).Decode(&v)decode while readingno full copy in memoryreads ahead; check More() for trailing data
Decoder.Token + More + Decode per elementwalk a huge array element by elementmemory per elementmore code
JSON Lines + Decode in a loopone value per linesimple streaming, resumableproducer must emit lines
io.ReadAll + json.Unmarshalbuffer then parsesimple, exact errorsmemory, no limit

SumArray in the chunked snippet decodes a 10,000-element array one item at a time; ReadEvents in the pipe snippet decodes JSON lines from a gzip stream. Encoder and decoder options are in JSON, XML, Struct Tags, Encoder/Decoder, Base64.

go
// Package chunked processes large inputs piece by piece: fixed-size chunks
// with io.ReadFull, lines with bufio.Scanner (and its token limit), a JSON
// array element by element with json.Decoder, and a line iterator.
package chunked

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"iter"
)

// Chunks calls fn with consecutive chunks of size bytes; the last may be shorter.
// Memory use is one chunk regardless of input size (think multipart upload parts).
func Chunks(r io.Reader, size int, fn func(part int, b []byte) error) error {
	buf := make([]byte, size)
	for part := 1; ; part++ {
		n, err := io.ReadFull(r, buf)
		if n > 0 {
			if ferr := fn(part, buf[:n]); ferr != nil {
				return ferr
			}
		}
		switch err {
		case nil:
			continue
		case io.EOF, io.ErrUnexpectedEOF: // no data, or a final short chunk
			return nil
		default:
			return err
		}
	}
}

// CountLines counts lines; maxLine raises bufio.Scanner's 64 KiB token limit.
func CountLines(r io.Reader, maxLine int) (int, error) {
	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 0, 64*1024), maxLine)
	n := 0
	for sc.Scan() {
		n++
	}
	return n, sc.Err() // bufio.ErrTooLong if a line exceeded maxLine
}

// Lines yields each line with its line number; it stops on the first error.
// It is an iterator over a Reader: pull bytes, push typed values.
func Lines(r io.Reader) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		sc := bufio.NewScanner(r)
		for i := 1; sc.Scan(); i++ {
			if !yield(i, sc.Text()) {
				return
			}
		}
	}
}

// Item is one element of a large JSON array.
type Item struct {
	ID    int     `json:"id"`
	Price float64 `json:"price"`
}

// SumArray decodes `[{"id":1,"price":2.5}, ...]` one element at a time.
func SumArray(r io.Reader) (count int, total float64, err error) {
	dec := json.NewDecoder(bufio.NewReader(r))
	tok, err := dec.Token()
	if err != nil {
		return 0, 0, err
	}
	if d, ok := tok.(json.Delim); !ok || d != '[' {
		return 0, 0, fmt.Errorf("chunked: expected array, got %v", tok)
	}
	for dec.More() {
		var it Item
		if err := dec.Decode(&it); err != nil {
			return count, total, err
		}
		count++
		total += it.Price
	}
	_, err = dec.Token() // closing ']'
	return count, total, err
}

// WriteReport writes with fmt.Fprintf through a bufio.Writer and flushes.
// Forgetting Flush loses the last (up to 4096) bytes silently.
func WriteReport(w io.Writer, rows map[string]int, order []string) error {
	bw := bufio.NewWriter(w)
	for _, k := range order {
		if _, err := fmt.Fprintf(bw, "%-10s %6d\n", k, rows[k]); err != nil {
			return err
		}
	}
	return bw.Flush()
}

Problem: HTTP bodies are streams: limit, decode, close ​

RuleServer sideClient side
Limit untrusted sizer.Body = http.MaxBytesReader(w, r.Body, max)io.LimitReader(resp.Body, max)
Decode while readingjson.NewDecoder(r.Body)same
Closethe server closes the request body for youdefer resp.Body.Close() always
Reuse connectionsafter the handler, the server itself drains up to 256 KiB of unread body (maxPostHandlerReadBytes) before reusing the connectiondrain (bounded) then close
Error typeerrors.As(err, &*http.MaxBytesError) -> 413non-2xx is not an error: check StatusCode

The net/http docs are explicit. MaxBytesReader is "similar to io.LimitReader but is intended for limiting the size of incoming request bodies ... returns a non-nil error of type *MaxBytesError for a Read beyond the limit, and closes the underlying reader when its Close method is called". For the client: "It is the caller's responsibility to close Body. The default HTTP client's Transport may not reuse HTTP/1.x 'keep-alive' TCP connections if the Body is not read to completion and closed."

go
// Package httpbody treats HTTP bodies as streams: cap untrusted request
// bodies with http.MaxBytesReader, decode JSON without io.ReadAll, and always
// drain and close response bodies so connections are reused.
package httpbody

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
)

// MaxBody is the largest request body the handler accepts.
const MaxBody = 1 << 20 // 1 MiB

// Order is the request payload.
type Order struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

// CreateOrder decodes straight from the capped body stream.
func CreateOrder(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, MaxBody)
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	var o Order
	if err := dec.Decode(&o); err != nil {
		var tooBig *http.MaxBytesError
		switch {
		case errors.As(err, &tooBig):
			http.Error(w, fmt.Sprintf("body larger than %d bytes", tooBig.Limit), http.StatusRequestEntityTooLarge)
		case errors.Is(err, io.EOF):
			http.Error(w, "empty body", http.StatusBadRequest)
		default:
			http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
		}
		return
	}
	// Reject trailing data such as `{"sku":"a"} {"sku":"b"}`.
	if dec.More() {
		http.Error(w, "one JSON object expected", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	_ = json.NewEncoder(w).Encode(o) // ResponseWriter is an io.Writer
}

// FetchJSON GETs url and decodes at most limit bytes of JSON into v.
// The deferred drain-and-close lets the Transport reuse the connection.
func FetchJSON(c *http.Client, url string, limit int64, v any) error {
	resp, err := c.Get(url)
	if err != nil {
		return err
	}
	defer func() {
		_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) // drain a bounded tail
		resp.Body.Close()
	}()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("GET %s: %s", url, resp.Status)
	}
	return json.NewDecoder(io.LimitReader(resp.Body, limit)).Decode(v)
}
$ go test -v ./httpbody
    httpbody_test.go:33: body larger than 1048576 bytes
    httpbody_test.go:47: truncated: bad json: unexpected EOF
    httpbody_test.go:47: unknown: bad json: json: unknown field "admin"
    httpbody_test.go:47: two: one JSON object expected
--- PASS: TestFetchJSONReusesConnection (0.00s)

TestFetchJSONReusesConnection counts new server connections over five requests and asserts exactly one, which holds because the body is drained and closed. Middlewares that wrap bodies (gzip, logging) are in Middlewares; upload storage in File Uploads, S3 & Serving from a CDN.

Problem: process a large file in chunks ​

SolutionHowAdvantageCost / limit
Fixed chunksio.ReadFull(r, buf) in a loop; last chunk short (ErrUnexpectedEOF)exact part sizes (S3 multipart uploads use fixed-size parts)one buffer of chunk size
Linesbufio.Scanner with Buffersimplest for texttoken limit
Records at offsetsio.NewSectionReader per worker over a ReaderAtparallel reads of one fileneeds record boundaries
Memory mapnot in the stdlib (syscall.Mmap, x/exp/mmap)fast random accessplatform specific

Chunks treats io.ErrUnexpectedEOF from ReadFull as "last, shorter chunk", which is the one place where that error is normal.

Problem: backpressure in a streaming pipeline ​

SolutionHowAdvantageCost / limit
Synchronous io.Pipewriter blocks until reader consumesproducer can never outrun consumertwo goroutines, no slack
io.Copy between socket and fileeach Write blocks when the kernel send buffer is fullTCP flow control reaches the sendernone; it is the default
Bounded buffer between stageschannel of []byte with capacity k, or bufio sizeabsorbs burstsmemory = k x chunk
Unbounded buffering (bytes.Buffer, ReadAll)read everything firstdecouples stagesmemory grows with input: avoid

Blocking Read/Write calls are backpressure: a slow S3 upload makes pw.Write block, which makes the JSON encoder wait, which makes the database cursor wait. Nothing piles up. The same idea at broker level (prefetch, consumer lag, load shedding) is in Backpressure & Flow Control.

Problem: stream a database export to a client ​

PostgreSQL's COPY ... TO STDOUT sends rows as a byte stream, and pgx exposes it as PgConn.CopyTo(ctx, w io.Writer, sql) (and CopyFrom(ctx, r io.Reader, sql) for import), so the export can go straight into a gzip writer wrapped around the http.ResponseWriter:

sql
-- streamed by pgconn.CopyTo(ctx, gzipOverResponseWriter, ...)
COPY (
  SELECT id, customer_id, total_cents, created_at
  FROM orders
  WHERE created_at >= now() - interval '30 days'
  ORDER BY id
) TO STDOUT WITH (FORMAT csv, HEADER true);

The database pushes, gzip compresses, the socket's flow control throttles; memory stays flat. Server-side cursors and database/sql row streaming are covered in Cursors & Streaming Results.

Choosing ​

SituationUseExtra techniqueReason
Accepting input in a functionio.Reader parameterask for ReaderAt/Seeker only if neededworks with every source, easy to test
Need exactly n bytesio.ReadFullErrUnexpectedEOF means truncatedone Read may return fewer
Whole input, small and trustedio.ReadAll / os.ReadFilesimplest
Untrusted inputhttp.MaxBytesReader / io.LimitReaderread limit+1 to detect overflowmemory exhaustion defence
Move bytes between two endsio.Copykeep concrete types for sendfile/splice32 KiB buffer or kernel fast path
Hot copy pathio.CopyBuffer + sync.Poolavoids 32 KiB allocation per call
Writer-producing code feeding a Reader-consuming APIio.PipeCloseWithError on failurestreaming with backpressure
Hash/count/store in one passio.MultiWriter or io.TeeReaderno second read
Many small writesbufio.Writercheck Flushfewer syscalls
Line-oriented textbufio.ScannerBuffer for long linessimplest correct loop
Replayable in-memory bodybytes.ReaderSeek(0, io.SeekStart)bytes.Buffer is consumed
Need cancellationdeadlines on net.Conn, request contextscontext.AfterFuncio has no ctx
Typed records inside the programiter.Seqdecode at the boundarytyped, for range

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Inside one process the rule is "accept interfaces, return concrete types" (Go Code Review Comments: interfaces "generally belong in the package that uses values of the interface type"). A report service exposes WriteReport(ctx, w io.Writer); the HTTP handler passes the ResponseWriter, the CLI passes os.Stdout, the test passes a bytes.Buffer. An import handler takes r.Body, wraps it in MaxBytesReader, and passes the Reader to a CSV parser that never sees HTTP. One rule prevents most incidents here: no io.ReadAll on input you did not create.

Modular monolith and multiple databases ​

Module boundaries should pass streams, not byte slices, when payloads can be large: the documents module exposes Open(id) (io.ReadCloser, error) and the billing module streams an invoice PDF from it into the response without holding it. Ownership of Close is part of the contract: whoever receives a ReadCloser closes it. When a module moves data between two databases (archive old orders from PostgreSQL to object storage), CopyTo into a gzip writer into an upload Reader through io.Pipe keeps memory flat and lets the slowest store set the pace.

Microservices ​

Across services, streams become HTTP bodies, gRPC streams or broker messages. An export flow: the API gateway receives GET /exports/orders.csv.gz, calls the orders service, which runs COPY ... TO STDOUT into gzip into its ResponseWriter; the gateway io.Copys the upstream resp.Body to its own ResponseWriter (a reverse proxy is exactly this). What must survive the hops: size limits at every entry point (each service applies its own MaxBytesReader; the gateway's limit does not protect a service reachable directly), deadlines at every hop (a stalled upstream must not hold a goroutine and a connection forever), and closing every resp.Body so connection pools do not drain. Large payloads usually do not travel through a broker at all: publish a reference (claim check) and stream the bytes from object storage. Service-level HTTP details are in net/http: Server, Client, 1.22 Routing.

Distributed data: replicas, caches, object storage ​

Object stores (S3 and compatible) accept uploads as Readers and return downloads as ReadClosers; multipart uploads want fixed-size parts (io.ReadFull chunks) and parallel range downloads map to io.NewOffsetWriter on one file. Integrity across copies uses a hash computed while streaming (MultiWriter(dst, sha256)) and compared on the other side; caches and CDNs key content by that digest. Replicated reads of large blobs should be resumable: a Range request from the last offset plus a SectionReader/Seek on the source. A partially written object must never become visible: write to a temporary key or file, check every Close error, then rename or complete the multipart upload.

Scaling path: 1x, 10x, 100x ​

LoadI/O concernAction
1xcorrectnesscorrect read loops, limits on input, close bodies, check Close on writers
10xallocation and syscallsbufio, CopyBuffer with pooled buffers, streaming decoders instead of ReadAll, measure with -benchmem
100xbandwidth and copieskeep sendfile/splice paths (no wrappers on file-to-socket copies), offload static files to a CDN, compress once and cache, per-tenant byte counters for fair limits, deadlines everywhere so slow clients cannot pin goroutines

Lab ​

Everything here runs on the host with Go only. Outputs marked "real" were captured during authoring (Go 1.27.4, module go 1.24). Setup:

bash
cd docs/snippets/go/io-readers-writers/go
gofmt -l . && go vet ./... && go test -race ./...
  1. The lost last chunk (real). go test -run TestCountBytesHandlesDataWithEOF -v ./contract prints correct loop: 13 bytes, err-first loop: 0 bytes. Change CountBytes to check err first and watch it fail.
  2. Truncation versus end (real). go test -run 'TestFrames|TestTruncatedFrame' -v ./contract prints contract: truncated frame: unexpected EOF; the clean end returns io.EOF.
  3. Copy path and short writes (real). go test -v ./copying shows copied 10 bytes, err: short write and recovered: empty buffer in CopyBuffer. Remove SpySource.WriteTo and confirm the path becomes dst.ReadFrom.
  4. Pipe semantics (real). go test -race -v ./pipe prints io: read/write on closed pipe. Now write pr, pw := io.Pipe(); pw.Write([]byte("x")); pr.Read(make([]byte, 1)) in a single main; expected (not run): fatal error: all goroutines are asleep - deadlock!.
  5. HTTP limits (real). go test -v ./httpbody prints body larger than 1048576 bytes and the 400 reasons. Delete the drain-and-close defer in FetchJSON and rerun TestFetchJSONReusesConnection; expected (not run here): more than one connection opened.
  6. Deadlines (real). go test -v ./deadline prints read pipe: i/o timeout and context deadline exceeded.
  7. Archive failure modes (real). go test -v ./archive prints archive short: EOF, gzip: invalid header, unexpected EOF.
  8. sendfile (expected, not run). On Linux, serve a 1 GiB file with io.Copy(conn, f) and run strace -f -e trace=sendfile,read,write ./server; expected: sendfile(...) calls and almost no read/write of the data. Wrap f in bufio.NewReader(f) and expected: a stream of read(..., 4096) and write calls.

Common misconceptions ​

BeliefReality
Read fills the bufferIt returns up to len(p); partial reads are normal
If err != nil, ignore nProcess n > 0 bytes first; data can come with io.EOF
io.EOF is a failureIt is the graceful end; io.Copy and ReadAll return nil
A Reader can return a wrapped EOFRead must return io.EOF itself; callers compare with ==
io.Copy returns io.EOF when doneIt returns nil on success; CopyN returns io.EOF if short
Write may write part and return nilNot allowed; io.Copy reports io.ErrShortWrite
defer w.Close() without checking is fine for writersgzip footers, tar trailers and deferred write errors live in Close
io.ReadAll is fine for request bodiesUnbounded memory; use MaxBytesReader and streaming decoders
io.LimitReader reports oversize inputIt truncates silently; read limit+1 and compare
io.Pipe buffers dataNo buffer; reader and writer must be in different goroutines
MultiWriter writes to the others when one failsIt stops at the first error
Wrapping a context check makes a Read cancellableOnly deadlines or Close interrupt a blocked Read
bufio.Writer output appears immediatelyOnly after Flush (or a full buffer)
Zero-copy needs special APIsPlain io.Copy with concrete *os.File/*net.TCPConn hits sendfile/splice
You must close the server-side request bodyThe server does; you must close the client-side response body

Cheat sheet ​

TopicWhat to remember
Read loopn, err := r.Read(buf); use buf[:n]; then if err == io.EOF { break }
Exact bytesio.ReadFull; io.ErrUnexpectedEOF = truncated, io.EOF = nothing read
At least nio.ReadAtLeast(r, buf, min); ErrShortBuffer if min > len(buf)
Whole inputio.ReadAll only with a limit
Writeall or error; io.ErrShortWrite from io.Copy otherwise
Closereverse order of wrapping; check errors on writers
Copyio.Copy (32 KiB), CopyN (exact), CopyBuffer (your buffer, not zero length)
Fast pathsWriterTo first, then ReaderFrom; sendfile, splice, copy_file_range
Pipetwo goroutines; CloseWithError to fail the reader; ErrClosedPipe for the writer
AdaptersMultiReader, MultiWriter, TeeReader, LimitReader, SectionReader, NopCloser, Discard
SeekSeekStart 0, SeekCurrent 1, SeekEnd 2; returns offset from start
bufio4096 B default, Flush, Scanner 64 KiB token limit, Buffer
In memorybytes.Buffer consumes, bytes.Reader/strings.Reader seek and replay
HTTPMaxBytesReader + json.Decoder; client: drain bounded, Body.Close()
CancellationSetReadDeadline, context.AfterFunc, request ctx; i/o timeout
Testingiotest.OneByteReader, HalfReader, DataErrReader, TestReader

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Reader returns 7, io.EOF. What must the caller do? Must-know ​

Answer

Answer: Use the 7 bytes, then stop with success. Discarding them because err != nil is the classic bug.

2 — io.ReadFull(r, buf[:8]) returns 5, io.ErrUnexpectedEOF. What happened, and when would it return io.EOF instead? Important ​

Answer

Answer: The stream ended after 5 of 8 bytes: truncated data. It returns io.EOF only if no byte at all was read.

3 — Why does io.Copy return nil and not io.EOF at the end? Must-know ​

Answer

Answer: Copy is defined to read until EOF, so reaching EOF is success, not an error to report.

4 — A custom Writer returns n < len(p), nil. What does io.Copy do? Important ​

Answer

Answer: It stops and returns io.ErrShortWrite, because the Writer contract requires a non-nil error when n < len(p).

5 — You wrap an *os.File in a counting reader before io.Copy(conn, r). What do you lose on Linux, and how do you get it back? Good to know ​

Answer

Answer: The sendfile fast path, because the wrapper hides the concrete type. Count via a wrapper that implements WriteTo/ReadFrom by delegating, or count with the returned n from io.Copy.

6 — Why does pr, pw := io.Pipe(); pw.Write(b); pr.Read(p) in one goroutine never finish? Important ​

Answer

Answer: The pipe has no buffer: Write blocks until a Read consumes the data, and that Read can never start in the same goroutine. The runtime reports all goroutines are asleep - deadlock!.

7 — How do you make the reader of a pipe see the producer's failure instead of a clean end? Important ​

Answer

Answer: Call pw.CloseWithError(err); reads then return err instead of io.EOF.

8 — io.LimitReader(body, 1<<20) protects memory. What does it not tell you, and how do you fix that? Must-know ​

Answer

Answer: Whether the input was larger: it truncates silently. Read limit+1 bytes and reject if you got more than limit, or use http.MaxBytesReader, which returns *http.MaxBytesError.

9 — Why must a client drain and close resp.Body? Must-know ​

Answer

Answer: Closing frees the connection; reading to EOF first lets the Transport reuse the HTTP/1.x keep-alive connection. Without it you leak connections and file descriptors.

10 — A goroutine is blocked in conn.Read. Your context is cancelled. How does the Read return? Important ​

Answer

Answer: Only by a deadline or Close on the connection: e.g. context.AfterFunc(ctx, func() { conn.SetReadDeadline(time.Unix(1, 0)) }). The Read then fails with an i/o timeout error matching os.ErrDeadlineExceeded.

11 — You need to send the same in-memory body again on retry. bytes.Buffer or bytes.Reader? Must-know ​

Answer

Answer: bytes.Reader: it can Seek(0, io.SeekStart) and is not consumed. A bytes.Buffer is empty after the first read.

12 — What do iotest.DataErrReader and iotest.OneByteReader find in your code? Good to know ​

Answer

Answer: Loops that drop data returned together with an error, and code that assumes one Read returns a whole message or fills the buffer.

Glossary ​

TermMeaning
io.ReaderInterface with Read(p []byte) (n int, err error)
io.WriterInterface with Write(p []byte) (n int, err error)
Read contractRules for Read: 0 <= n <= len(p), data before error, EOF semantics, do not retain p
n > 0 with errA Read that returns data and an error in the same call
partial readA Read that returns fewer bytes than len(p); normal
io.EOFSentinel for a graceful end of input
io.ErrUnexpectedEOFEnd of input inside a fixed-size block
io.ErrShortWriteA write accepted fewer bytes without returning an error
io.ErrShortBufferBuffer too small for the requested read
io.ErrClosedPipeRead or write on a closed io.Pipe end
io.ErrNoProgressRepeated 0, nil reads
io.ReadFullRead exactly len(buf) bytes
io.ReadAtLeastRead at least min bytes
io.ReadAllRead everything into memory
io.CloserInterface with Close() error
ReadCloser / WriteCloserReader or Writer plus Closer
io.CopyStream from Reader to Writer until EOF
io.CopyNCopy exactly n bytes
io.CopyBufferCopy through a caller-supplied buffer
WriterToOptional interface: source writes itself to a Writer
ReaderFromOptional interface: destination reads from a Reader
sendfileLinux/BSD/macOS syscall copying file data to a socket inside the kernel
spliceLinux syscall moving data between descriptors via a pipe buffer in the kernel
copy_file_rangeLinux syscall copying between files inside the kernel
zero-copyMoving data without copying it through user-space buffers
io.PipeSynchronous in-memory pipe without buffering
PipeReader / PipeWriterThe read and write halves of io.Pipe
CloseWithErrorClose a pipe end so the other side sees a chosen error
MultiReaderConcatenation of Readers
MultiWriterWriter that duplicates each write
TeeReaderReader that writes what it reads to a Writer
LimitReaderReader that returns EOF after n bytes
SectionReaderRead/Seek/ReadAt over a section of a ReaderAt
OffsetWriterWriter mapping writes to an offset of a WriterAt
NopCloserAdds a no-op Close to a Reader
io.DiscardWriter that discards everything
ReadSeekerReader plus Seeker
SeekMove the read/write offset
SeekStart / SeekCurrent / SeekEndWhence values 0, 1, 2
whenceThe reference point for a Seek offset
ReaderAtRead at an absolute offset; parallel-safe
bufioPackage with buffered Reader, Writer and Scanner
FlushPush buffered bytes to the underlying Writer
bufio.ScannerToken reader with split functions and a token limit
bytes.BufferGrowable in-memory Reader/Writer; reading consumes
strings.ReaderSeekable Reader over a string
bytes.ReaderSeekable Reader over a byte slice
StringWriterInterface with WriteString(s string)
fmt.FprintfFormatted output to any Writer
counting writerWriter adapter that counts bytes written
hashing writerA hash.Hash used as a Writer
compositionWrapping Readers/Writers in layers
gzipcompress/gzip Reader and Writer for the gzip format
tararchive/tar Reader and Writer for tape archives
streaming JSONDecoding JSON from a Reader with json.Decoder
backpressureA slow consumer slowing the producer instead of buffering
http.MaxBytesReaderRequest body limiter returning *http.MaxBytesError
Body.CloseClosing an HTTP body to free the connection
deadlineAbsolute time after which an I/O call fails
iotesttesting/iotest, helpers for testing Readers
custom ReaderYour own type with a Read method
iteratoriter.Seq function that yields typed values
php:// streamPHP's built-in I/O stream wrapper (php://input, php://temp...)
stream filterPHP transformation attached to a stream

For PHP/Laravel developers ​

PHP has the same idea under a different name: streams. A stream resource (fopen) is a Reader and Writer at once, wrappers (file://, http://, php://, compress.zlib://) play the role of Go's concrete types, and stream filters play the role of wrapping Readers.

PHPGoDifference
fopen('php://input', 'r')r.BodyPHP: "It can be opened and read as many times as needed"; Go's body can be read once
php://memory, php://tempbytes.Buffer, temp filephp://temp switches to a file after 2 MB; Go has no automatic switch
php://stdin, php://stdoutos.Stdin, os.Stdoutsame descriptors
stream_copy_to_stream($in, $out)io.Copy(out, in)both stream; Go adds sendfile/splice fast paths
stream_filter_append($fp, 'string.rot13')wrap: Rot13{R: r}PHP filters are registered by name; Go wraps types
compress.zlib://file.gzgzip.NewReader(f)
feof($fp) before readingio.EOF returned by ReadGo learns about the end from the read itself
file_get_contents($url)io.ReadAll(resp.Body)both load everything; both need limits
PHP-FPM ends the request and frees everythinglong-lived processan unclosed Go body leaks until restart
php
$in  = fopen('php://input', 'rb');
$out = fopen('compress.zlib:///tmp/upload.gz', 'wb');
stream_filter_append($in, 'string.rot13');      // transform while reading
$bytes = stream_copy_to_stream($in, $out, 10 * 1024 * 1024);  // with a cap
fclose($out);                                    // writes the gzip footer, like zw.Close()

The habits that transfer: cap the size, stream instead of file_get_contents, close writers to flush compression footers. The habit that does not: in Laravel, $request->getContent() and $request->file() are prepared before your controller runs, so the framework has already buffered the body; in Go the handler receives the live socket stream and decides itself how much to read.

References ​

Built by Morteza Negahi