Skip to content

Instantly share code, notes, and snippets.

@maliqq
Last active November 22, 2018 08:53
Show Gist options
  • Save maliqq/5869555 to your computer and use it in GitHub Desktop.
Save maliqq/5869555 to your computer and use it in GitHub Desktop.
Golang message broker
package protocol
import (
"fmt"
"log"
)
// pubsub
type Broker struct {
Send map[string]*chan *Message
}
func (broker *Broker) Bind(key string, channel *chan *Message) {
broker.Send[key] = channel
}
func (broker *Broker) Unbind(key string) {
delete(broker.Send, key)
}
// route
type Notify struct {
All bool
None bool
One string
Only []string
Except []string
}
func (n *Notify) String() string {
s := "[NOTIFY]"
if n.All {
s += " all"
}
if n.None {
s += " mone"
}
if n.One != "" {
s += fmt.Sprintf(" one: %v", n.One)
}
if len(n.Except) != 0 {
s += fmt.Sprintf(" except: %v", n.Except)
}
if len(n.Only) != 0 {
s += fmt.Sprintf(" only: %v", n.Only)
}
return s
}
func NewBroker() *Broker {
return &Broker{
Send: map[string]*chan *Message{},
}
}
func (broker *Broker) Dispatch(msg *Message, n *Notify) {
log.Printf("%s | %s\n", n.String(), msg.String())
if n.None {
return
}
if n.One != "" {
*broker.Send[n.One] <- msg
return
}
for key, send := range broker.Send {
if !n.All {
var skip bool
if len(n.Only) != 0 {
skip = true
for _, Only := range n.Only {
if Only == key {
skip = false
break
}
}
}
if len(n.Except) != 0 {
skip = false
for _, Except := range n.Except {
if Except == key {
skip = true
break
}
}
}
if skip {
continue
}
}
*send <- msg
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment