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 ofio.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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why two tiny interfaces run everything | Why it exists |
| Go 1, ioutil deprecation, 1.22 fast paths | Where it comes from |
n > 0 with err, partial reads | io.Reader and the Read contract |
io.EOF, 0, nil | io.EOF and the end of a stream |
io.ReadFull, io.ReadAtLeast, io.ErrUnexpectedEOF | Reading an exact amount |
io.ReadAll and memory | io.ReadAll |
io.ErrShortWrite, StringWriter | io.Writer and short writes |
Close, ReadCloser, WriteCloser | io.Closer and its combinations |
io.Copy, io.CopyN, io.CopyBuffer | Copying |
WriterTo, ReaderFrom, sendfile, splice | Fast paths and zero-copy |
io.Pipe, CloseWithError, io.ErrClosedPipe | io.Pipe |
MultiReader, TeeReader, LimitReader, NopCloser, Discard | The adapter set |
Seek, SeekStart, SeekCurrent, SeekEnd, SectionReader | Seeker and random access |
bufio.Reader, bufio.Writer, Scanner, Flush | bufio |
bytes.Buffer, strings.Reader, bytes.Reader | In-memory readers and writers |
Counting writer, hashing writer, Fprintf | Writer adapters |
Implementing Read yourself | A custom Reader |
Timeouts, cancellation, SetReadDeadline | Deadlines and context |
testing/iotest | Testing readers |
io.Reader versus iter.Seq | Readers and iterators |
| Exact error texts | Mechanics |
| tar.gz, streaming JSON, HTTP bodies, chunks | Solving the classic problems |
PHP streams, php://temp, stream filters | For PHP/Laravel developers |
| Reproduce the outputs | Lab |
Everything in one minute
The interfaces.
| Interface | Method | In plain words | Implemented by |
|---|---|---|---|
io.Reader | Read(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.Writer | Write(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.Closer | Close() error | Release the resource, flush trailers | files, sockets, bodies, gzip.Writer |
io.Seeker | Seek(offset int64, whence int) (int64, error) | Move the cursor | *os.File, bytes.Reader, strings.Reader, io.SectionReader |
io.ReaderAt | ReadAt(p []byte, off int64) | Read at an offset, parallel-safe | *os.File, bytes.Reader, strings.Reader |
io.WriterTo | WriteTo(w Writer) (int64, error) | "I can push myself into w efficiently" | bytes.Buffer, strings.Reader, *os.File, *net.TCPConn |
io.ReaderFrom | ReadFrom(r Reader) (int64, error) | "I can pull from r efficiently" | bytes.Buffer, *os.File, *net.TCPConn, bufio.Writer, io.Discard |
io.StringWriter | WriteString(s string) (int, error) | Write a string without converting | bytes.Buffer, strings.Builder, bufio.Writer, *os.File |
ReadCloser, WriteCloser, ReadSeeker, ReadWriter... | embedded combinations | Exactly the union of the parts | as above |
The helpers.
| Helper | What it does | Ends with |
|---|---|---|
io.Copy(dst, src) | Stream src into dst until EOF | err == nil on success, not io.EOF |
io.CopyN(dst, src, n) | Copy exactly n bytes | io.EOF if src was shorter |
io.CopyBuffer(dst, src, buf) | Copy through your buffer | panics if len(buf) == 0 |
io.ReadFull(r, buf) | Fill buf completely | io.ErrUnexpectedEOF if cut in the middle |
io.ReadAtLeast(r, buf, min) | Read at least min bytes | io.ErrShortBuffer if min > len(buf) |
io.ReadAll(r) | Everything into one slice | memory = input size |
io.WriteString(w, s) | Uses WriteString if present | |
io.LimitReader(r, n) | EOF after n bytes | silent truncation |
io.TeeReader(r, w) | Every byte read is also written to w | write errors become read errors |
io.MultiReader(rs...) | Concatenate readers | |
io.MultiWriter(ws...) | Duplicate each write | stops at the first failing writer |
io.NewSectionReader(ra, off, n) | Window over a ReaderAt | |
io.Pipe() | Synchronous in-memory pipe | needs two goroutines |
io.NopCloser(r) | Add a no-op Close | |
io.Discard | Writer that swallows everything |
The errors.
| Error | Text | Meaning |
|---|---|---|
io.EOF | EOF | Graceful end of input; compare with == or errors.Is |
io.ErrUnexpectedEOF | unexpected EOF | Input ended inside a fixed-size block |
io.ErrShortWrite | short write | A Writer took fewer bytes and returned no error |
io.ErrShortBuffer | short buffer | The buffer you passed is too small |
io.ErrClosedPipe | io: read/write on closed pipe | Other end of an io.Pipe was closed |
io.ErrNoProgress | multiple Read calls return no data or error | A broken Reader keeps returning 0, nil |
*http.MaxBytesError | http: request body too large | Body went past http.MaxBytesReader |
bufio.ErrTooLong | bufio.Scanner: token too long | A 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, smaller | Richer, faster |
|---|---|
| One-method interfaces: easy to implement, easy to fake in tests | Optional extra interfaces (WriterTo, ReaderFrom, ReaderAt, StringWriter) discovered at run time |
| Caller owns the buffer: no allocation per call | Caller must handle partial reads correctly |
| Streaming: memory independent of input size | No random access unless the source also offers Seeker/ReaderAt |
| No context parameter: interfaces stay tiny | Cancellation needs deadlines or wrappers |
Errors are values: io.EOF is a sentinel | Easy 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
- "
Readfills my buffer." It reads up tolen(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. Useio.ReadFullwhen you need exactly n. - "If
err != nilI can ignoren." A Reader may return the last bytes andio.EOFin the same call. Checking the error first throws those bytes away (io.Reader and the Read contract). - "
io.ReadAllis 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:
| Version | Change |
|---|---|
| Go 1.16 | io/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.19 | http.MaxBytesReader returns the typed error *http.MaxBytesError |
| Go 1.20 | io.OffsetWriter (the write-side twin of SectionReader) |
| Go 1.21 | context.AfterFunc, useful to turn cancellation into a deadline |
| Go 1.22 | io.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.23 | range-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 lostReal 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.
| Return | Meaning | Caller action |
|---|---|---|
n > 0, nil | Data, more may follow | Use p[:n], read again |
n > 0, io.EOF | Last data and the end | Use p[:n], stop with success |
0, io.EOF | End | Stop with success |
n >= 0, other err | Failure, maybe after data | Use p[:n] if meaningful, return err |
0, nil | Nothing 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.
// 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.
| Situation | Correct error |
|---|---|
| No more records, clean boundary | io.EOF |
| Stream ended inside a record | io.ErrUnexpectedEOF |
| Stream ended inside a gzip member | unexpected EOF from compress/gzip |
| Peer reset the TCP connection | read: connection reset by peer (a *net.OpError) |
| JSON value incomplete | unexpected 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.ErrUnexpectedEOFReal 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.
| Call | Empty input | Partial input | Enough input |
|---|---|---|---|
r.Read(buf) | 0, io.EOF | k, nil or k, io.EOF | any n <= len(buf) |
io.ReadFull(r, buf) | 0, io.EOF | k, io.ErrUnexpectedEOF | len(buf), nil |
io.ReadAtLeast(r, buf, min) | 0, io.EOF | k, io.ErrUnexpectedEOF | n >= min, nil |
io.ReadAtLeast with min > len(buf) | 0, io.ErrShortBuffer | same | same |
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 lostReal 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.
| Need | Instead of ReadAll |
|---|---|
| Decode JSON | json.NewDecoder(r).Decode(&v) with a limit |
| Store to disk/S3 | io.Copy(dst, r) |
| Hash | io.Copy(h, r) |
| Need bytes, but bounded | io.ReadAll(io.LimitReader(r, max+1)) then check len > max |
| Count lines | bufio.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.ErrShortWriteReal 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."
| Writer | Can it fail? | Notes |
|---|---|---|
*os.File | yes | ENOSPC, EBADF, permissions |
net.Conn | yes | broken pipe, connection reset, deadline |
http.ResponseWriter | yes | client went away; first Write sends headers |
hash.Hash | no | "It never returns an error." |
bytes.Buffer | no (panics on ErrTooLarge) | WriteString err "is always nil" |
bufio.Writer | yes, sticky | data reaches the target only on Flush |
io.Discard | no | also 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.
| Type | Close does | Error worth checking? |
|---|---|---|
*os.File (read) | release fd | rarely |
*os.File (write) | release fd, may report write error | yes |
gzip.Writer | flush, write footer | yes, always |
tar.Writer | write end-of-archive | yes |
bufio.Writer | has no Close; call Flush | yes |
http.Response.Body | return connection to pool (if drained) | no, but always call it |
*io.PipeWriter | reader gets io.EOF | always 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, nilReal 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.
// 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/copyingFast 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 copyReal 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 destination | Mechanism (Linux) | Lost when |
|---|---|---|
*os.File to *net.TCPConn | sendfile(2) | file wrapped, TLS in between |
TCP/Unix socket to *net.TCPConn | splice(2) | either side wrapped |
*net.TCPConn to *net.UnixConn | splice(2) (Go 1.22) | wrapped |
*os.File to *net.UnixConn | sendfile(2) (Go 1.22) | wrapped |
*os.File to *os.File | copy_file_range(2), else splice | destination O_APPEND |
bytes.Buffer, strings.Reader to anything | WriteTo: one Write of the whole content | wrapped |
anything to io.Discard | ReadFrom 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 exitsReal 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.
// 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:
| Adapter | Doc 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 errors | hash an upload while a decoder reads it |
io.LimitReader(r, n) | "stops with EOF after n bytes"; a *LimitedReader whose N counts down | cap untrusted input |
io.NopCloser(r) | "a ReadCloser with a no-op Close method"; forwards WriterTo | tests, 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 section | one part of a file |
io.NewOffsetWriter(wa, off) | maps writes to offset off | parallel 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.
// 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.
| Type | Seeker | ReaderAt | Notes |
|---|---|---|---|
*os.File | yes | yes | Seek on a pipe/terminal fails |
*bytes.Reader, *strings.Reader | yes | yes | also WriterTo |
*bytes.Buffer | no | no | consumed as read |
*io.SectionReader | yes | yes | window over a ReaderAt |
net.Conn, http.Request.Body, gzip.Reader | no | no | forward 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 reportedReal 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.
| Tool | Default | Knob | Error |
|---|---|---|---|
bufio.Reader | 4096 B | NewReaderSize | bufio: buffer full (ErrBufferFull) from ReadSlice/Peek |
bufio.Writer | 4096 B | NewWriterSize | sticky first write error |
bufio.Scanner | 64 KiB max token | Buffer(buf, max) | bufio.Scanner: token too long |
ReadString('\n') | unbounded | returns data plus io.EOF if no final newline | |
ReadLine | buffer size | low-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-readableReal 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.
| Type | Read | Write | Seek | Re-read | Use for |
|---|---|---|---|---|---|
bytes.Buffer | consumes | yes | no | no | assembling output, FIFO |
bytes.Reader | yes | no | yes | yes | replayable bodies, ReaderAt |
strings.Reader | yes | no | yes | yes | feeding strings to Reader APIs |
strings.Builder | no | yes | no | n/a | building 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 databaseReal 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.
| Adapter | Implements | Note |
|---|---|---|
| Counting writer | Write | count n, not len(p) |
| Hashing writer | hash.Hash is a Writer | h.Sum(nil) at the end |
io.MultiWriter(dst, h) | fan-out | stops at the first error |
| Rate-limited writer | Write with rate.Limiter.WaitN | see rate limiting |
| Prefix/log writer | iotest.NewWriteLogger(prefix, w) | debugging |
fmt.Fprintf | any io.Writer | returns 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.EOFReal 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.
// 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.
| Source | Interrupt a blocked Read with | Error |
|---|---|---|
net.Conn (TCP, Unix, net.Pipe) | SetReadDeadline, Close | i/o timeout / use of closed network connection |
*os.File pipe or FIFO | SetReadDeadline, Close | i/o timeout / file already closed |
regular *os.File | not interruptible (disk reads finish) | |
http.Request.Body (server) | server ReadTimeout, ResponseController | i/o timeout |
http.Response.Body (client) | request ctx, Client.Timeout | context deadline exceeded |
io.PipeReader | CloseWithError on either side | your error |
| any Reader between reads | ctx.Err() check wrapper | context canceled |
// 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:
| Function | Behaviour |
|---|---|
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, NewWriteLogger | log 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 keptReal 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 neededReal 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.Reader | iter.Seq | |
|---|---|---|
| Unit | bytes | typed values |
| Who drives | consumer pulls with its buffer | producer pushes into the loop body |
| Composes with | io.Copy, gzip, tar, net, hash | for range, slices.Collect, maps |
| Errors | (n, err) per call | must be a value in the sequence or a side channel |
| Early stop | stop calling Read, Close | break |
Mechanics
Exact messages and what they mean Must-know
| Message | Where it comes from | Meaning and fix |
|---|---|---|
EOF | io.EOF | normal end; handle as success in loops |
unexpected EOF | io.ErrUnexpectedEOF, gzip, json, tar | input cut in the middle; treat as corrupt/truncated |
short write | io.ErrShortWrite | a Writer broke the contract; fix the Writer |
short buffer | io.ErrShortBuffer | ReadAtLeast with min > len(buf) |
io: read/write on closed pipe | io.ErrClosedPipe | the other end of the pipe was closed |
multiple Read calls return no data or error | io.ErrNoProgress (bufio) | a Reader keeps returning 0, nil |
empty buffer in CopyBuffer | panic in io.CopyBuffer | passed make([]byte, 0) |
Seek: invalid offset | SectionReader.Seek | negative resulting position |
http: request body too large | *http.MaxBytesError | body over MaxBytesReader limit; answer 413 |
bufio.Scanner: token too long | bufio.ErrTooLong | line over the Scanner max; call Buffer |
bufio: buffer full | bufio.ErrBufferFull | ReadSlice/Peek longer than the buffer |
bytes.Buffer: too large | panic bytes.ErrTooLarge | buffer could not grow; stream instead |
gzip: invalid header | gzip.ErrHeader | input is not gzip (often already decompressed) |
read pipe: i/o timeout / read tcp ...: i/o timeout | os.ErrDeadlineExceeded | deadline passed |
context deadline exceeded | context.DeadlineExceeded | the request context ended |
write: broken pipe | syscall.EPIPE | peer closed; stop writing |
fatal error: all goroutines are asleep - deadlock! | runtime | io.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
| Item | Value (Go 1.25 source) | Change with |
|---|---|---|
io.Copy buffer | 32 KiB (32 * 1024), smaller for a LimitedReader | io.CopyBuffer |
io.ReadAll initial capacity | 512 bytes, grows by append | read into a pre-sized buffer if size is known |
bufio default size | 4096 bytes | NewReaderSize, NewWriterSize |
bufio.MaxScanTokenSize | 64 KiB | Scanner.Buffer(buf, max) |
bytes.Buffer first allocation | 64 bytes (smallBufferSize) | Grow(n) |
http.MaxBytesReader | your n; negative treated as 0 | per route |
json.Decoder | own buffering; may read beyond the value | Decoder.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
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
| Layered writers | tar.NewWriter(gzip.NewWriter(f)), close tar then gzip then file | constant memory, any destination | close order and errors matter |
| Layered readers | tar.NewReader(gzip.NewReader(f)), tr.Next() per entry | stream entries; tr is the entry Reader | must validate names and sizes |
os.ReadFile + bytes.Reader | whole file in memory | simple | memory = archive size |
// 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
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
json.NewDecoder(r).Decode(&v) | decode while reading | no full copy in memory | reads ahead; check More() for trailing data |
Decoder.Token + More + Decode per element | walk a huge array element by element | memory per element | more code |
JSON Lines + Decode in a loop | one value per line | simple streaming, resumable | producer must emit lines |
io.ReadAll + json.Unmarshal | buffer then parse | simple, exact errors | memory, 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.
// 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
| Rule | Server side | Client side |
|---|---|---|
| Limit untrusted size | r.Body = http.MaxBytesReader(w, r.Body, max) | io.LimitReader(resp.Body, max) |
| Decode while reading | json.NewDecoder(r.Body) | same |
| Close | the server closes the request body for you | defer resp.Body.Close() always |
| Reuse connections | after the handler, the server itself drains up to 256 KiB of unread body (maxPostHandlerReadBytes) before reusing the connection | drain (bounded) then close |
| Error type | errors.As(err, &*http.MaxBytesError) -> 413 | non-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."
// 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
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
| Fixed chunks | io.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 |
| Lines | bufio.Scanner with Buffer | simplest for text | token limit |
| Records at offsets | io.NewSectionReader per worker over a ReaderAt | parallel reads of one file | needs record boundaries |
| Memory map | not in the stdlib (syscall.Mmap, x/exp/mmap) | fast random access | platform 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
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
Synchronous io.Pipe | writer blocks until reader consumes | producer can never outrun consumer | two goroutines, no slack |
io.Copy between socket and file | each Write blocks when the kernel send buffer is full | TCP flow control reaches the sender | none; it is the default |
| Bounded buffer between stages | channel of []byte with capacity k, or bufio size | absorbs bursts | memory = k x chunk |
Unbounded buffering (bytes.Buffer, ReadAll) | read everything first | decouples stages | memory 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:
-- 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
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Accepting input in a function | io.Reader parameter | ask for ReaderAt/Seeker only if needed | works with every source, easy to test |
| Need exactly n bytes | io.ReadFull | ErrUnexpectedEOF means truncated | one Read may return fewer |
| Whole input, small and trusted | io.ReadAll / os.ReadFile | simplest | |
| Untrusted input | http.MaxBytesReader / io.LimitReader | read limit+1 to detect overflow | memory exhaustion defence |
| Move bytes between two ends | io.Copy | keep concrete types for sendfile/splice | 32 KiB buffer or kernel fast path |
| Hot copy path | io.CopyBuffer + sync.Pool | avoids 32 KiB allocation per call | |
| Writer-producing code feeding a Reader-consuming API | io.Pipe | CloseWithError on failure | streaming with backpressure |
| Hash/count/store in one pass | io.MultiWriter or io.TeeReader | no second read | |
| Many small writes | bufio.Writer | check Flush | fewer syscalls |
| Line-oriented text | bufio.Scanner | Buffer for long lines | simplest correct loop |
| Replayable in-memory body | bytes.Reader | Seek(0, io.SeekStart) | bytes.Buffer is consumed |
| Need cancellation | deadlines on net.Conn, request contexts | context.AfterFunc | io has no ctx |
| Typed records inside the program | iter.Seq | decode at the boundary | typed, 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
| Load | I/O concern | Action |
|---|---|---|
| 1x | correctness | correct read loops, limits on input, close bodies, check Close on writers |
| 10x | allocation and syscalls | bufio, CopyBuffer with pooled buffers, streaming decoders instead of ReadAll, measure with -benchmem |
| 100x | bandwidth and copies | keep 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:
cd docs/snippets/go/io-readers-writers/go
gofmt -l . && go vet ./... && go test -race ./...- The lost last chunk (real).
go test -run TestCountBytesHandlesDataWithEOF -v ./contractprintscorrect loop: 13 bytes, err-first loop: 0 bytes. ChangeCountBytesto checkerrfirst and watch it fail. - Truncation versus end (real).
go test -run 'TestFrames|TestTruncatedFrame' -v ./contractprintscontract: truncated frame: unexpected EOF; the clean end returnsio.EOF. - Copy path and short writes (real).
go test -v ./copyingshowscopied 10 bytes, err: short writeandrecovered: empty buffer in CopyBuffer. RemoveSpySource.WriteToand confirm the path becomesdst.ReadFrom. - Pipe semantics (real).
go test -race -v ./pipeprintsio: read/write on closed pipe. Now writepr, pw := io.Pipe(); pw.Write([]byte("x")); pr.Read(make([]byte, 1))in a singlemain; expected (not run):fatal error: all goroutines are asleep - deadlock!. - HTTP limits (real).
go test -v ./httpbodyprintsbody larger than 1048576 bytesand the 400 reasons. Delete the drain-and-closedeferinFetchJSONand rerunTestFetchJSONReusesConnection; expected (not run here): more than one connection opened. - Deadlines (real).
go test -v ./deadlineprintsread pipe: i/o timeoutandcontext deadline exceeded. - Archive failure modes (real).
go test -v ./archiveprintsarchive short: EOF,gzip: invalid header,unexpected EOF. - sendfile (expected, not run). On Linux, serve a 1 GiB file with
io.Copy(conn, f)and runstrace -f -e trace=sendfile,read,write ./server; expected:sendfile(...)calls and almost noread/writeof the data. Wrapfinbufio.NewReader(f)and expected: a stream ofread(..., 4096)andwritecalls.
Common misconceptions
| Belief | Reality |
|---|---|
Read fills the buffer | It returns up to len(p); partial reads are normal |
If err != nil, ignore n | Process n > 0 bytes first; data can come with io.EOF |
io.EOF is a failure | It is the graceful end; io.Copy and ReadAll return nil |
| A Reader can return a wrapped EOF | Read must return io.EOF itself; callers compare with == |
io.Copy returns io.EOF when done | It returns nil on success; CopyN returns io.EOF if short |
Write may write part and return nil | Not allowed; io.Copy reports io.ErrShortWrite |
defer w.Close() without checking is fine for writers | gzip footers, tar trailers and deferred write errors live in Close |
io.ReadAll is fine for request bodies | Unbounded memory; use MaxBytesReader and streaming decoders |
io.LimitReader reports oversize input | It truncates silently; read limit+1 and compare |
io.Pipe buffers data | No buffer; reader and writer must be in different goroutines |
MultiWriter writes to the others when one fails | It stops at the first error |
| Wrapping a context check makes a Read cancellable | Only deadlines or Close interrupt a blocked Read |
bufio.Writer output appears immediately | Only after Flush (or a full buffer) |
| Zero-copy needs special APIs | Plain io.Copy with concrete *os.File/*net.TCPConn hits sendfile/splice |
| You must close the server-side request body | The server does; you must close the client-side response body |
Cheat sheet
| Topic | What to remember |
|---|---|
| Read loop | n, err := r.Read(buf); use buf[:n]; then if err == io.EOF { break } |
| Exact bytes | io.ReadFull; io.ErrUnexpectedEOF = truncated, io.EOF = nothing read |
| At least n | io.ReadAtLeast(r, buf, min); ErrShortBuffer if min > len(buf) |
| Whole input | io.ReadAll only with a limit |
| Write | all or error; io.ErrShortWrite from io.Copy otherwise |
| Close | reverse order of wrapping; check errors on writers |
| Copy | io.Copy (32 KiB), CopyN (exact), CopyBuffer (your buffer, not zero length) |
| Fast paths | WriterTo first, then ReaderFrom; sendfile, splice, copy_file_range |
| Pipe | two goroutines; CloseWithError to fail the reader; ErrClosedPipe for the writer |
| Adapters | MultiReader, MultiWriter, TeeReader, LimitReader, SectionReader, NopCloser, Discard |
| Seek | SeekStart 0, SeekCurrent 1, SeekEnd 2; returns offset from start |
| bufio | 4096 B default, Flush, Scanner 64 KiB token limit, Buffer |
| In memory | bytes.Buffer consumes, bytes.Reader/strings.Reader seek and replay |
| HTTP | MaxBytesReader + json.Decoder; client: drain bounded, Body.Close() |
| Cancellation | SetReadDeadline, context.AfterFunc, request ctx; i/o timeout |
| Testing | iotest.OneByteReader, HalfReader, DataErrReader, TestReader |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
io.Reader | Interface with Read(p []byte) (n int, err error) |
io.Writer | Interface with Write(p []byte) (n int, err error) |
| Read contract | Rules for Read: 0 <= n <= len(p), data before error, EOF semantics, do not retain p |
| n > 0 with err | A Read that returns data and an error in the same call |
| partial read | A Read that returns fewer bytes than len(p); normal |
io.EOF | Sentinel for a graceful end of input |
io.ErrUnexpectedEOF | End of input inside a fixed-size block |
io.ErrShortWrite | A write accepted fewer bytes without returning an error |
io.ErrShortBuffer | Buffer too small for the requested read |
io.ErrClosedPipe | Read or write on a closed io.Pipe end |
io.ErrNoProgress | Repeated 0, nil reads |
io.ReadFull | Read exactly len(buf) bytes |
io.ReadAtLeast | Read at least min bytes |
io.ReadAll | Read everything into memory |
io.Closer | Interface with Close() error |
| ReadCloser / WriteCloser | Reader or Writer plus Closer |
io.Copy | Stream from Reader to Writer until EOF |
io.CopyN | Copy exactly n bytes |
io.CopyBuffer | Copy through a caller-supplied buffer |
| WriterTo | Optional interface: source writes itself to a Writer |
| ReaderFrom | Optional interface: destination reads from a Reader |
| sendfile | Linux/BSD/macOS syscall copying file data to a socket inside the kernel |
| splice | Linux syscall moving data between descriptors via a pipe buffer in the kernel |
| copy_file_range | Linux syscall copying between files inside the kernel |
| zero-copy | Moving data without copying it through user-space buffers |
io.Pipe | Synchronous in-memory pipe without buffering |
| PipeReader / PipeWriter | The read and write halves of io.Pipe |
| CloseWithError | Close a pipe end so the other side sees a chosen error |
| MultiReader | Concatenation of Readers |
| MultiWriter | Writer that duplicates each write |
| TeeReader | Reader that writes what it reads to a Writer |
| LimitReader | Reader that returns EOF after n bytes |
| SectionReader | Read/Seek/ReadAt over a section of a ReaderAt |
| OffsetWriter | Writer mapping writes to an offset of a WriterAt |
| NopCloser | Adds a no-op Close to a Reader |
io.Discard | Writer that discards everything |
| ReadSeeker | Reader plus Seeker |
| Seek | Move the read/write offset |
| SeekStart / SeekCurrent / SeekEnd | Whence values 0, 1, 2 |
| whence | The reference point for a Seek offset |
| ReaderAt | Read at an absolute offset; parallel-safe |
| bufio | Package with buffered Reader, Writer and Scanner |
| Flush | Push buffered bytes to the underlying Writer |
bufio.Scanner | Token reader with split functions and a token limit |
| bytes.Buffer | Growable in-memory Reader/Writer; reading consumes |
| strings.Reader | Seekable Reader over a string |
| bytes.Reader | Seekable Reader over a byte slice |
| StringWriter | Interface with WriteString(s string) |
fmt.Fprintf | Formatted output to any Writer |
| counting writer | Writer adapter that counts bytes written |
| hashing writer | A hash.Hash used as a Writer |
| composition | Wrapping Readers/Writers in layers |
| gzip | compress/gzip Reader and Writer for the gzip format |
| tar | archive/tar Reader and Writer for tape archives |
| streaming JSON | Decoding JSON from a Reader with json.Decoder |
| backpressure | A slow consumer slowing the producer instead of buffering |
http.MaxBytesReader | Request body limiter returning *http.MaxBytesError |
| Body.Close | Closing an HTTP body to free the connection |
| deadline | Absolute time after which an I/O call fails |
iotest | testing/iotest, helpers for testing Readers |
| custom Reader | Your own type with a Read method |
| iterator | iter.Seq function that yields typed values |
| php:// stream | PHP's built-in I/O stream wrapper (php://input, php://temp...) |
| stream filter | PHP 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.
| PHP | Go | Difference |
|---|---|---|
fopen('php://input', 'r') | r.Body | PHP: "It can be opened and read as many times as needed"; Go's body can be read once |
php://memory, php://temp | bytes.Buffer, temp file | php://temp switches to a file after 2 MB; Go has no automatic switch |
php://stdin, php://stdout | os.Stdin, os.Stdout | same 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.gz | gzip.NewReader(f) | |
feof($fp) before reading | io.EOF returned by Read | Go 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 everything | long-lived process | an unclosed Go body leaks until restart |
$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
- io package source, Go 1.25.0:
Reader,Writer,Closer,Seeker,ReaderAt,WriterTo,ReaderFrom,ReadFull,ReadAtLeast,Copy,CopyN,CopyBuffer,LimitReader,SectionReader,OffsetWriter,TeeReader,Discard,NopCloser,ReadAll, error values (pkg.go.dev returned 403 to automated fetches, so the package source was read instead) - io.Pipe source, Go 1.25.0:
Pipe,PipeReader,PipeWriter,CloseWithError,ErrClosedPipe - io.MultiReader and MultiWriter source, Go 1.25.0
- testing/iotest source, Go 1.25.0 and logger.go
- bufio source, Go 1.25.0 and scan.go
- bytes.Buffer source, Go 1.25.0 and strings.Reader source
- net/http request.go, Go 1.25.0:
MaxBytesReader,MaxBytesError,Request.Body - net/http response.go, Go 1.25.0 and client.go: closing and draining
Response.Body - net tcpsock_posix.go, Go 1.25.0, sendfile.go, splice_linux.go:
TCPConn.ReadFrom/WriteTofast paths - os zero_copy_linux.go, Go 1.25.0:
copy_file_range,splice,sendfilefor*os.File - compress/gzip gunzip.go, archive/tar reader.go, encoding/json stream.go, hash/hash.go
- The Go Programming Language Specification: interface types and embedding
- Effective Go: interface names,
io.ReadWriterembedding,Fprintf - Go FAQ and The Go Memory Model: interface satisfaction, concurrency of shared Readers
- Go Code Review Comments: where interfaces belong
- Go 1.16 release notes:
io/ioutildeprecation; Go 1.19:MaxBytesError; Go 1.20:OffsetWriter; Go 1.21:context.AfterFunc; Go 1.22:splice/sendfileinio.Copy; Go 1.23: iterators; Go 1.24; Go 1.25 - Go blog: Pipelines and cancellation, Range over function types, Errors are values
- pgx pgconn source:
CopyTo(ctx, w io.Writer, sql),CopyFrom(ctx, r io.Reader, sql) - PHP manual: php:// wrappers, List of available filters, stream_filter_append
- Secondary, not fetched (blocked by the host): Ben Johnson, "Go Walkthrough: io package" (Medium, go-walkthrough series). Nothing on this page depends on it.