Help us shape the future of Go! Take the 2026 Go Developer Survey

dispatcher

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2019 License: MIT Imports: 5 Imported by: 1

README

GO Dispatcher

Build Status Codecov branch GoDoc Go Report Card License

A simple event dispatcher made in Go.

Install

Use go get.

$ go get github.com/vsmoraes/go-dispatcher

Then import the package into your own code:

import "github.com/vsmoraes/go-dispacher"

Usage

package main

import (
	"context"
	"log"
	
	"github.com/vsmoraes/go-dispatcher"
)

type User struct {
	Name  string
	Email string
}

var UserWasCreated dispatcher.EventType = "user-was-created"

type UserCreated struct {
	User User
}

func (uc UserCreated) Type() dispatcher.EventType {
	return UserWasCreated
}

func (uc UserCreated) Data() interface{} {
	return uc.User
}

func OnUserCreated(ctx context.Context, e dispatcher.Event) {
	log.Printf("A user was created: %v", e.Data())
}

func main() {
	d := dispatcher.New()
	d.On(UserWasCreated, OnUserCreated)
	
	if err := d.Dispatch(context.Bachground(), e); err != nil {
		log.Fatalf("failed to dispatch event: %v", err)
	}
}

License

This project is released under the MIT licence. See LICENSE for more details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrListenerNotFound = errors.New("listener not found")
)

Functions

This section is empty.

Types

type Dispatcher

type Dispatcher interface {
	// On registers an event listener to events of a given type.
	On(EventType, ListenerFunc)

	// Dispatch fires an event of a given type.
	Dispatch(context.Context, Event)
}

func New

func New() Dispatcher

New creates a new Dispatcher instance.

type Event

type Event interface {
	Type() EventType
	Data() interface{}
}

Event defines the type and the data of an event.

type EventType

type EventType string

EventType defines the kind of the dispatched event.

func (EventType) String

func (et EventType) String() string

String returns the converted name of the event.

type ListenerFunc

type ListenerFunc func(context.Context, Event)

ListenerFunc is a function that can receive events.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL