Working with pipes
If you have a piece of code that expects a reader and another piece of code that expects a writer, you can connect the two using io.Pipe
.
Connecting code expecting a reader with code expecting a writer
A good example of this use case is preparing an HTTP POST
request, which requires a reader. If you have all of the data available, or if you already have a reader (such as os.File
), you can use that. However, if the data is produced by a function that takes a writer, use a pipe.
How to do it...
A pipe is a synchronously connected reader and writer. That is, if you write to a pipe, there must be a reader consuming from it concurrently. So make sure you put the data-producing side (where you use the writer) in a different goroutine than the data-consuming side (where you use the reader).
- Create a pipe reader and pipe writer using
io.Pipe
:pipeReader, pipeWriter := io.Pipe()
pipeReader
will read everything written topipeWriter
. - Use
pipeWriter
to...