Codementor Events

Golang: IO pipeline and broadcast

Published Jul 28, 2018
Golang: IO pipeline and broadcast

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:

Discover and read more posts from Hau Ma Van
get started
post commentsBe the first to share your opinion
Show more replies