Level: IntermediateGo Lang

Go Reader and Writer Interfaces Explained Simply

8 min read
Go Reader and Writer featured image: io.Reader, io.Writer and io.Copy cards

The Go Reader and Writer interfaces are two tiny interfaces that move data between files, networks, strings and more. In this post, you will learn how io.Reader and io.Writer work and why almost every Go program uses them. Then we will build a custom reader and writer and test six useful helpers.

This lesson builds on Go interfaces and Go file handling. We also use ideas from Go methods and receivers and Go strings. So it helps to read those first.

What Are Go Reader and Writer Interfaces?

A reader is anything you can read bytes from. Likewise, a writer is anything you can write bytes to. In Go, each idea is an interface with exactly one method. The io.Reader interface has Read, and the io.Writer interface has Write.

Think of water pipes. A tap is a source, while a bucket is a place to store water. You can join any tap to any bucket with a pipe, as long as the ends fit. In the same way, the Go Reader and Writer interfaces are the ends that fit. A file, a network connection, a string and a buffer can all join together, since they share the same ends.

Because the interfaces are so small, hundreds of types in the standard library satisfy them. Besides, they are easy to remember. As a result, a function that accepts an io.Reader works with all of them without any change. This is the main strength of the Go Reader and Writer interfaces.

Why Go Reader and Writer Interfaces Matter

Without a shared idea, every source would need its own code. For instance, you would write one function for files, one for network data and one for strings. Here is what the Go Reader and Writer interfaces give you.

  • Reuse: one function works with files, sockets, buffers and strings.
  • Streaming: you handle data piece by piece, so memory use stays low.
  • Easy testing: you can test with a string instead of a real file.
  • Composition: small tools snap together like building blocks.

Also, many packages follow the same style. For example, the json package decodes from any reader, and fmt.Fprintf prints to any writer. Therefore, learning the Go Reader and Writer interfaces opens up a large part of the standard library.

How Go Reader and Writer Interfaces Work

Both signatures are short. Read(p []byte) (n int, err error) fills your slice with up to len(p) bytes and says how many it wrote. Likewise, Write(p []byte) (n int, err error) takes your bytes and says how many it accepted.

Go Reader and Writer diagram showing files, strings and connections feeding io.Copy and three writers receiving data
A Reader supplies bytes, a Writer receives them, and io.Copy moves data from one to the other in small chunks. Files, strings and network connections all fit either end.

How Read Signals the End

A reader tells you it has no more data by returning the special error io.EOF. This is not a real failure, because it is just the end marker. Helper functions such as io.ReadAll and io.Copy handle it for you. So you rarely see it.

Why Streaming Saves Memory

Suppose you copy a 2 GB file. When you load it all into memory first, you need 2 GB of RAM. With io.Copy, Go reads a small chunk, writes it and then repeats. So the memory use stays tiny, even for huge files.

Types That Already Satisfy Reader and Writer

You rarely need to write your own types, because the standard library already has many. The table below shows common ones.

TypeReaderWriterTypical use
os.FileYesYesFiles on disk
strings.ReaderYesNoTests and small text
bytes.BufferYesYesBuild or collect bytes in memory
net.ConnYesYesNetwork connections
http.Request bodyYesNoData sent by a client
http.ResponseWriterNoYesData sent to a client

Notice that http.ResponseWriter is a writer. Because of that, you can pass it straight to fmt.Fprintf or json.NewEncoder. Similarly, a request body is a reader, so you can hand it to json.NewDecoder. Our Go JSON guide uses exactly this style.

Buffering for Speed

Reading one byte at a time from a file is slow, because each call asks the system for data. The bufio package solves this. It wraps a reader with a buffer. Then the system is asked for a large block only once in a while. In the same way, bufio.Writer batches small writes. Remember to call Flush at the end, or the last bytes may never leave the buffer.

Go Reader and Writer: Helpers at a Glance

The io package ships helpers that build on the two interfaces. The table below lists the ones we use in this lesson.

HelperWhat it doesTypical use
io.CopyMoves all data from a reader to a writerCopy a file or a response
io.ReadAllReads everything into memorySmall bodies and tests
io.LimitReaderStops after N bytesProtect against huge uploads
io.TeeReaderCopies what is read into a writerLog or hash while reading
io.MultiWriterSends one write to many writersLog to screen and file
bufio.ScannerReads line by lineText files and input
Go Reader and Writer diagram showing a reader wrapped by LimitReader and upperReader and copied to a MultiWriter
Wrapping readers and writers: a LimitReader wraps a source, a custom upper-case reader wraps another reader, and a MultiWriter fans one write out to three places.

These helpers all return or accept readers and writers. For that reason, you can stack them like blocks. For example, you can limit a reader, then tee it into a hash and finally copy it to a file.

Go Reader and Writer Hands-On: Six Examples

Now let’s write the code. First we make two small types of our own, and then we use the helpers.

Step 1: Your Own Reader and Writer

First, upperReader wraps another reader. Its Read method calls the inner reader and upper-cases the bytes that came back. Next, countWriter counts the bytes written through it.

type upperReader struct{ r io.Reader }

func (u upperReader) Read(p []byte) (int, error) {
	n, err := u.r.Read(p)
	copy(p, bytes.ToUpper(p[:n]))
	return n, err
}

type countWriter struct{ n int }

func (c *countWriter) Write(p []byte) (int, error) {
	c.n += len(p)
	return len(p), nil
}

Let’s look at the key lines. In upperReader, we only touch the first n bytes, because the rest of the slice holds old data. We also return err as it is, so that io.EOF passes through. In countWriter, we use a pointer receiver, because the counter must keep growing between calls.

Step 2: Use Them with the Helpers

Then main tries six ideas one after another. We print a short line after each step, so the output is easy to read.

func main() {
	src := strings.NewReader("hello from a string\n")
	n, _ := io.Copy(os.Stdout, src)
	fmt.Println("copied bytes:", n)

	io.Copy(os.Stdout, upperReader{strings.NewReader("quiet text\n")})

	sc := bufio.NewScanner(strings.NewReader("line one\nline two\nline three"))
	for sc.Scan() {
		fmt.Println("scanned:", sc.Text())
	}

	var buf bytes.Buffer
	cw := &countWriter{}
	mw := io.MultiWriter(&buf, cw, os.Stdout)
	fmt.Fprintln(mw, "logged twice")
	fmt.Printf("buffer=%q counted=%d\n", buf.String(), cw.n)

	lim := io.LimitReader(strings.NewReader("0123456789"), 4)
	b, _ := io.ReadAll(lim)
	fmt.Println("limited:", string(b))

	var seen bytes.Buffer
	tee := io.TeeReader(strings.NewReader("tee data"), &seen)
	io.ReadAll(tee)
	fmt.Println("tee saw:", seen.String())
}

Here is the real output from our run.

hello from a string
copied bytes: 20
QUIET TEXT
scanned: line one
scanned: line two
scanned: line three
logged twice
buffer="logged twice\n" counted=13
limited: 0123
tee saw: tee data

As you can see, io.Copy sent a string to the screen and reported 20 bytes. Then our custom reader changed the text to upper case on the way through. The scanner gave us one line at a time. Next, MultiWriter wrote the same message to the screen, to a buffer and to our counter, which saw 13 bytes. After that, the limit reader stopped after four characters. Finally, the tee reader kept a copy of what passed by. These lines show the Go Reader and Writer interfaces doing real work. Also, none of the helpers knew about our types.

Common Mistakes with Go Reader and Writer Interfaces

  • Ignoring the byte count: a reader may return fewer bytes than the slice holds. So always use n, not len(p).
  • Treating io.EOF as a failure: it only means the data ended. Therefore, check for it before you log an error.
  • Reading a huge body with io.ReadAll: this can fill the memory. Instead, wrap the reader in io.LimitReader first.
  • Forgetting to close: files and response bodies need Close. So use defer right after a successful open.
  • Writing with a value receiver when state is needed: the counter would reset on every call. For that reason, use a pointer receiver.

Best Practices for Go Reader and Writer Interfaces

  • Accept io.Reader and io.Writer in your functions, because callers can then pass files, buffers or strings.
  • Return concrete types when you create something, since callers get all its methods.
  • Use strings.NewReader in tests, which avoids real files.
  • Wrap readers instead of copying data, because wrapping keeps memory use low.
  • Limit untrusted input, since a client can send any amount of data.
  • Keep your own Read and Write methods small, so they follow the interface rules.

Practice Task

To practise the Go Reader and Writer interfaces, write a rot13Reader that wraps another reader and applies ROT13 to letters. Then copy "Uryyb" through it to the screen.

Hint: follow the pattern of upperReader. Loop over the first n bytes of p, and change only letters. After that, run it twice in a row and check that you get the original text back.

Official Resources

These pages describe the packages and ideas used in this lesson.

Quick Recap

  • The Go Reader and Writer interfaces each have one method, Read and Write.
  • A reader signals the end of data with io.EOF.
  • io.Copy moves data in small chunks, so memory use stays low.
  • Helpers such as LimitReader, TeeReader and MultiWriter wrap readers and writers.
  • Accept the interfaces in your functions, and tests become simple.
  • You can stack helpers to build small data pipelines.

What’s Next?

By now, you can read, write and combine data from any source. That wraps up this group of lessons on building real services in Go. Later, we will keep going with more practical topics for your daily work.

Coming soon: Go build tags and conditional compilation