Created
March 11, 2019 08:19
-
-
Save kasvith/73ed06d9dbde0371180b83817a00145f to your computer and use it in GitHub Desktop.
A simple eventbus written with go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
type Data struct { | |
data interface{} | |
topic string | |
} | |
type ChannelSlice []chan Data | |
type EventBus struct { | |
subscribers map[string] ChannelSlice | |
rm sync.RWMutex | |
} | |
func (eb *EventBus)publish(topic string, data interface{}) { | |
eb.rm.RLock() | |
if ch, found := eb.subscribers[topic]; found { | |
go _boradcastEvent(Data{data: data, topic:topic}, ch) | |
} | |
eb.rm.RUnlock() | |
} | |
func _boradcastEvent(data Data, sl ChannelSlice) { | |
for _, ch := range sl { | |
ch <- data | |
} | |
} | |
func (eb *EventBus)subscribe(topic string, ch chan Data) { | |
eb.rm.Lock() | |
if prev, found := eb.subscribers[topic]; found { | |
eb.subscribers[topic] = append(prev, ch) | |
} else { | |
eb.subscribers[topic] = append([] chan Data{}, ch) | |
} | |
eb.rm.Unlock() | |
} | |
var eb = &EventBus{ | |
subscribers: map[string]ChannelSlice{}, | |
} | |
func printData(ch string, data Data) { | |
fmt.Printf("Channel: %s; Topic: %s; Data: %v\n", ch, data.topic, data.data) | |
} | |
func publisTo(topic string, data string) { | |
for { | |
eb.publish(topic, data) | |
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) | |
} | |
} | |
func main() { | |
ch1 := make(chan Data) | |
ch2 := make(chan Data) | |
ch3 := make(chan Data) | |
eb.subscribe("topic1", ch1) | |
eb.subscribe("topic2", ch2) | |
eb.subscribe("topic2", ch3) | |
go publisTo("topic1", "Hi topic 1") | |
go publisTo("topic2", "Welcome to topic 2") | |
for { | |
select { | |
case d := <-ch1: | |
go printData("ch1", d) | |
case d := <-ch2: | |
go printData("ch2", d) | |
case d := <-ch3: | |
go printData("ch3", d) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment