io.Reader
as written by Mat Ryer and David Hernandez in The Pace Dev Blog.io.Reader
.io.Reader
when we've opened files, encoded JSON and various other common tasks. It's a simple abstraction over reading data from somethingio.Reader
you can gain a lot of re-use from the standard library, it's a very commonly used abstraction (along with its counterpart io.Writer
)context
to provide cancellation. This is especially useful if you're performing tasks which may be computationally expensive and you want to be able to stop them.io.Reader
you have no guarantees over speed, it could take 1 nanosecond or hundreds of hours. You might find it useful to be able to cancel these kind of tasks in your own application and that's what Mat and David wrote about.context.Context
and io.Reader
) to solve this problem.io.Reader
so it can be cancelled.io.Reader
you're usually supplying it to some other function and you dont really concern yourself with the details; such as json.NewDecoder
or ioutil.ReadAll
.Given anio.Reader
with "ABCDEF", when I send a cancel signal half-way through I when I try to continue to read I get nothing else so all I get is "ABC"
Reader
's Read
method will read the contents it has into a []byte
that we supply.io.Reader
from a string with some dataio.Reader
with a context.Context
.io.Reader
io.Reader
we pass inio.Reader
and this test will give us confidence as we move forward.context.Context
with cancellation so we can cancel
after the first readctx
to our functioncancel
nothing was readcontext.Background
too)io.Reader
that we read from and the context.Context
so let's create that and try and return it from our function instead of the original io.Reader
io.Reader
) so let's add the method.io.Reader
context.Context
to see if it has been cancelled.context.Context
. This allows callers of the code to inspect the various reasons cancellation has occurred and this is covered more in the original post.io.Reader
) with another you usually want to reach for the delegation patternIn software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance.