io.Reader in depth

This article aims to convince you to use io.Reader in your own code wherever you can.

Let’s have a look at io.Reader:

type Reader interface {
Read(p []byte) (n int, err error)
}

Examples of readers

There are many kinds of Reader types available in the standard library, and you’ve almost certainly used at least one of them.

var r io.Reader
var err error
r, err = os.Open("file.txt")
var r io.Reader
r = strings.NewReader("Read will return these bytes")
var r io.Reader
r = request.Body
var r io.Reader
var buf bytes.Buffer
r = &buf

Using readers

Now we have a few Reader types — let’s explore ways in which they can be used.

p := make([]byte, 256)
n, err := r.Read(p)
b, err := ioutil.ReadAll(r)
n, err := io.Copy(w, r)
err := json.NewDecoder(r).Decode(v)
r = gzip.NewReader(r)

Take io.Reader when you can

If you’re designing a package or utility (even if it’s an internal thing that nobody will ever see) rather than taking in strings or []byte slices, consider taking in an io.Reader if you can for data sources. Because suddenly, your code will work with every type that implements io.Reader.

func Reverse(s string) (string, error)
func Reverse(r io.Reader) io.Reader
r = Reverse(strings.NewReader("Make me backwards"))
f, err := os.Open("file.txt")
if err != nil {
log.Fatalln(err)
}
r = Reverse(f)
func handle(w http.ResponseWriter, r *http.Request) {  rev := Reverse(r.Body)  // etc...
}

--

--

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mat Ryer

Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints