I'm trying to build a service in Go which delays a live stream (socketio/signalR) for ~7 minutes. It should also allow a non-delayed stream. So the Go service should have something like a buffer or a queue that forces data to wait for the specified duration before it is allowed to be consumed. How would you do something like this in Go? Would the delayed stream be a seperate goroutine? What data structure should be used to delay the data?
My current idea would be to use the time
package to wait/tick for 7 minutes before the data is allowed to be consumed but this blocking behavior might not be optimal in this scenario.
Here is some code to explain what I'm trying to do. FakeStream
is a mock function that simulates the live streamed data I'm getting from the external service.
package main
import (
"fmt"
"time"
)
func DelayStream(input chan string, output chan string, delay string) {
// not working for some reason
// delayDuration, _ := time.ParseDuration(delay)
// fmt.Println(delayDuration.Seconds())
if delay == "5s" {
fmt.Println("sleeping")
time.Sleep(5 * time.Second)
}
data := <-input
output <- data
}
func FakeStream(live chan string) {
ticks := time.Tick(2 * time.Second)
for now := range ticks {
live <- fmt.Sprintf("%v", now.Format(time.UnixDate))
}
}
func main() {
liveData := make(chan string)
delayedData := make(chan string)
go FakeStream(liveData)
go DelayStream(liveData, delayedData, "5s")
for {
select {
case live := <-liveData:
fmt.Println("live: ", live)
case delayed := <-delayedData:
fmt.Println("delayed: ", delayed)
}
}
}
For some reason the delayed channel only outputs once and it doesn't output the expected data. It should output the first thing in the live channel but it doesn't.