Golang: IO pipeline and broadcast

Kelvin Ma
1 min readMay 29, 2018

--

How do you upload a file to multiple destination at once?

I’ll introduce to you guys Golang IO pipeline and IO copier to do that

io.Pipe

Go io Pipe make a “pipe” that wrote into writer will come out at reader

reader, writer := io.Pipe()

Broadcaster

Linked channel broadcaster can be found at https://github.com/hauxe/GoM/tree/master/broadcast

broadcaster := broadcast.NewBroadcaster()

We will broad cast to file and stdout, so create two listener for broadcaster

fileComsumer, err := broadcaster.Listen()if err != nil {    panic(err)}stdoutComsumer, err := broadcaster.Listen()if err != nil {    panic(err)}

io.TeeReader

In write function we use TeeReader to write to destination and take a copy of reader to broadcast to next listener

Note that you must perform a final read on final TeeReader to trigger the io pipeline

Full working codes:

--

--

Kelvin Ma

Gather together the things that change for the same reasons. Separate those things that change for different reasons.