Nearly every useful program does I/O. Reading a configuration file, responding to an HTTP request and processing a stream of sensor data all come down to bytes moving from one place to another. Go's io package describes that flow with two small interfaces, io.Reader and io.Writer. Each has a single method, so once you understand their contract you can work with files, network connections, in-memory buffers, compressed streams and test fakes through the same API.
The io.Reader interface
io.Reader is defined with a single method:
type Reader interface { Read(p []byte) (n int, err error)}Read reads up to len(p) bytes from the underlying data source and places them into p. It returns the number of bytes actually read (n) and any error that occurred.
The contract has one rule that surprises many Go newcomers: always process the n bytes returned before inspecting the error. Read is allowed to return a non-zero n alongside a non-nil error. A real read might deliver a few valid bytes and also signal that the stream is exhausted, both in a single call. If you check the error first and stop, you silently discard the bytes that were read.
The sentinel error io.EOF signals that the source is exhausted. Nothing went wrong; there is just nothing more to read. Any valid content that arrived in the same call as io.EOF should still be processed.
Reading in a loop
Most real reads require multiple calls to Read, because the source is larger than the buffer or the underlying transport delivers data in chunks. The correct pattern is:
buf := make([]byte, 4096)for { n, err := r.Read(buf) process(buf[:n]) // always process n bytes first if err == io.EOF { break } if err != nil { log.Fatal(err) }}The loop processes buf[:n] on every iteration, including the one where io.EOF arrives, and only exits when the source is fully consumed or an unexpected error occurs.
For cases where you want all content in memory at once, io.ReadAll handles the loop for you:
data, err := io.ReadAll(r)if err != nil { log.Fatal(err)}io.ReadAll is convenient for small or bounded sources. Avoid it for streams of unknown or potentially large size, where holding all bytes in memory at once could be a problem.
Common io.Reader implementations
Because io.Reader requires only a single method, the standard library is full of types that satisfy it. Several appear in almost every Go program.
os.File is the most common starting point. Opening a file returns a *os.File that implements io.Reader, letting you pass it directly to any function expecting a reader:
f, err := os.Open("data.txt")if err != nil { log.Fatal(err)}defer f.Close()data, err := io.ReadAll(f)strings.NewReader creates a reader from a string. It is especially useful in tests, where you want to supply known input to a function that expects an io.Reader without creating a temporary file:
r := strings.NewReader("hello, world")data, _ := io.ReadAll(r)fmt.Println(string(data)) // hello, worldbufio.NewReader wraps any io.Reader and adds an internal buffer, reducing system calls when reading byte-by-byte or line-by-line:
br := bufio.NewReader(f)line, err := br.ReadString('\n')http.Request.Body is an io.Reader that delivers the raw bytes of an incoming HTTP request body. This means any code that reads from an io.Reader can process HTTP bodies without knowing anything about HTTP:
func handler(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } // use body}bytes.Buffer is an in-memory byte buffer that satisfies both io.Reader and io.Writer. It is useful when you need to build data and then read it back, for example when constructing a request body or buffering output before flushing it:
var buf bytes.Bufferbuf.WriteString("hello")data, _ := io.ReadAll(&buf)fmt.Println(string(data)) // helloThe io.Writer interface
io.Writer mirrors io.Reader on the output side:
type Writer interface { Write(p []byte) (n int, err error)}Write writes len(p) bytes from p to the underlying sink. It returns the number of bytes written (n) and any error that stopped the write early. The contract imposes two obligations: if n < len(p), the implementation must return a non-nil error, and it must not modify the slice p, because the caller retains ownership and may reuse it immediately after Write returns.
Implementing io.Writer
Satisfying io.Writer is straightforward as long as you respect the contract. Here is a writer that counts the total bytes written across all calls:
type CountingWriter struct { w io.Writer total int}func (cw *CountingWriter) Write(p []byte) (int, error) { n, err := cw.w.Write(p) cw.total += n return n, err}CountingWriter delegates to an underlying writer and accumulates how much data has flowed through. Any code expecting an io.Writer can use it transparently. The standard library uses the same pattern, wrapping a writer to add behavior, to build compressed writers, hash-computing writers and multi-writers.
Common io.Writer implementations
*os.File lets you write to files and to standard streams. os.Stdout and os.Stderr are pre-opened *os.File values that implement io.Writer, so you can pass them directly to any function expecting a writer:
fmt.Fprintln(os.Stdout, "hello")f, err := os.Create("output.txt")if err != nil { log.Fatal(err)}defer f.Close()f.Write([]byte("some content\n"))http.ResponseWriter is an io.Writer that writes to the body of an HTTP response. Any function that writes to an io.Writer can write to an HTTP client without modification:
func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello, client")}bytes.Buffer accumulates written bytes in memory and can be read back as a []byte or string. It is useful for building output incrementally before consuming it all at once:
var buf bytes.Bufferfmt.Fprintf(&buf, "name: %s, age: %d", "Alice", 30)fmt.Println(buf.String()) // name: Alice, age: 30Composing I/O with io.Copy
Any reader can feed any writer, and io.Copy is the most direct example:
func Copy(dst Writer, src Reader) (written int64, err error)io.Copy reads from src in chunks and writes each chunk to dst until src is exhausted or an error occurs. It handles the read loop, buffer management, and partial-write errors for you:
src, err := os.Open("input.txt")if err != nil { log.Fatal(err)}defer src.Close()dst, err := os.Create("output.txt")if err != nil { log.Fatal(err)}defer dst.Close()n, err := io.Copy(dst, src)fmt.Printf("copied %d bytes\n", n)The same call works if src is an HTTP body, a strings.Reader, or any other io.Reader. The dst could be a file, a network socket or a bytes.Buffer. io.Copy only knows about the two interfaces.
Functions across the standard library accept io.Reader or io.Writer for the same reason. fmt.Fprintf writes formatted output to any io.Writer, json.NewDecoder reads JSON from any io.Reader, and gzip.NewWriter compresses whatever you write into it before passing it on to an io.Writer. They all work with your own types too.