Kenny Jue

home  about
      

gotopic

September 09, 2019

Project Cover by MatthewJFrith

About This Project

gotopic is a utility package for handling events across many goroutines.

  • producers publish events under a topic.

  • These events are processed by a broker.

  • The broker broadcasts the events to all consumers that have subscribed to that topic.

  • The consumers will handle the processing of each event.

  • A broker uses a basic underlying bipartite graph which builds relationships between topics and subscribed consumers.

V1 was completed on October 6, 2019, but the project has since been overhauled to a V2 to implement optimizations and best practices. It currently remains private.

Installation

go get github.com/pixeltopic/gotopic

Example

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/pixeltopic/gotopic"
)

const (
	fooTopic = "fooTopic"
	barTopic = "barTopic"

	fooProducer = "fooProd"
	fooConsumer = "fooCons"
)

func main() {
	broker := gotopic.NewBroker()
	broker.RegisterTopics(fooTopic, barTopic)

	producer := broker.GetOrRegisterProducer(fooProducer)
	consumer := broker.GetOrRegisterConsumer(fooConsumer)

	// Add a thread-safe handler to process incoming Events.
	consumer.AddHandler("fooHandler", func(e gotopic.Event) error {
		switch e.Topic() {
		case fooTopic:
			if val, ok := e.Payload().(string); ok {
				fmt.Printf("foohandler says, '%s!'\n", val)
			}
		case barTopic:
			log.Fatal("I'm not subscribed to this topic!")
		default:
			log.Printf("fooHandler defaulted")
		}
		return nil
	})

	consumer.Subscribe(fooTopic)

	producer.Publish(broker.CreateEvent(fooTopic, "foo best"))
	producer.Publish(broker.CreateEvent(barTopic, nil))

	<-time.After(1 * time.Second)
}

Dependencies Used

  • gomock/mockgen for mocking interfaces
  • ginkgo, a BDD-style Go testing framework
  • gomega to supplement ginkgo

Links

None for now.