There are many ways to do it but this is a very simple example of traffic lights flows.


package main

import (
"fmt"
"time"
)

func main() {
closeChan := make(chan struct{})
go func() {
time.Sleep(time.Second * 10)
closeChan <- struct{}{}
}()

trafficLight := TrafficLight{
Colours: []string{"red", "red amber", "green", "amber"},
Delay: time.Second * 2,
Close: closeChan,
}

trafficLight.On()
}

// 1. Red: Stop
// 2. Red/Amber: Get ready
// 3. Green: Go
// 4. Amber: Stop if safe
type TrafficLight struct {
Colours []string
Delay time.Duration
Close chan struct{}
}

func (t TrafficLight) On() {
go func() {
tick := time.NewTicker(t.Delay)
defer tick.Stop()

len := len(t.Colours)

for i := 0; i < len; i++ {
fmt.Println(t.Colours[i])

if i == len-1 {
i = -1
}

<-tick.C
}
}()

<-t.Close
}