Skip to content

Instantly share code, notes, and snippets.

@blinkinglight
Last active August 29, 2015 14:21
Show Gist options
  • Save blinkinglight/e00b8e2a425a35cb07e8 to your computer and use it in GitHub Desktop.
Save blinkinglight/e00b8e2a425a35cb07e8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/tuxychandru/pubsub"
"time"
)
type Event struct {
Command string
Payload interface{}
}
type DemoStruct struct {
A string
B string
C interface{}
}
var pub *pubsub.PubSub = pubsub.New(8)
var events map[string]func(interface{}) = make(map[string]func(interface{}))
func RunTask(name string, payload interface{}) {
ev := &Event{name, payload}
pub.Pub(ev, "events")
}
func main() {
events["restart_app"] = func(payload interface{}) {
fmt.Printf("Restart app: %v\n", payload)
}
events["update_urls"] = func(payload interface{}) {
fmt.Printf("update urls: %v\n", payload)
}
events["print_struct"] = func(payload interface{}) {
fmt.Printf("struct: %q -> %+v\n", payload, payload)
}
fmt.Println("hi")
go func() {
ch := pub.Sub("pirmas")
for {
select {
case m := <-ch:
fmt.Printf("pirmas: %v\n", m)
}
}
}()
go func() {
ch := pub.Sub("antras")
for {
select {
case m := <-ch:
fmt.Printf("antras: %v\n", m)
}
}
}()
go func() {
ch := pub.Sub("events")
for {
select {
case m := <-ch:
if f, ok := events[m.(*Event).Command]; ok != false {
go f(m.(*Event).Payload)
}
}
}
}()
go func() {
for {
t := <-time.Tick(3 * time.Second)
pub.Pub(t, "pirmas")
pub.Pub(fmt.Sprintf("%v -> siaip\n", t), "antras")
}
}()
time.Sleep(1 * time.Second)
RunTask("restart_app", "")
RunTask("update_urls", "http://meh/blah")
RunTask("print_struct", &DemoStruct{"test", "doh", "meh"})
w := make(chan struct{})
<-w
}
// output
/*
hi
Restart app:
update urls: http://meh/blah
struct: &{"test" "doh" "meh"} -> &{A:test B:doh C:meh}
pirmas: 2015-05-21 13:05:46.584448256 +0300 EEST
antras: 2015-05-21 13:05:46.584448256 +0300 EEST -> siaip
*/
/* pubsub // async // jobs // events */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment