This commit is contained in:
mamor87 2025-09-16 22:33:13 +02:00
commit 1133202fa4
12 changed files with 343 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.idea
.vscode

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Markus Morgenstern
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

75
README.md Normal file
View File

@ -0,0 +1,75 @@
# Events
This events package in Go provides a simple and robust implementation for a publish-subscribe pattern (Pub/Sub). It enables you to create events that can contain generic data and distribute these events to registered listeners. The package is concurrently safe thanks to the internal use of mutex locks, making it ideal for multithreaded applications.
This package is perfect for decoupling components in your application. Instead of modules depending directly on each other, they can communicate via events. For example:
- A user module can publish a UserCreatedEvent.
- An email module can subscribe to this event to automatically send a welcome email without directly calling the user module.
## Core features
- Generic events: Create events with any data type (NewEvent[T]). The generic implementation ensures that events are strongly typed, improving code safety and readability.
- Secure data extraction: The Data method enables secure extraction of event data by passing a pointer. It automatically checks for type matching and ensures that the target pointer can be set to avoid common runtime errors.
- Simple subscription management: Subscribe to events using the Subscribe method. Each subscription returns an ISubscription instance that provides a simple Unsubscribe method. This makes it easy to cleanly remove event handlers.
- Concurrency-safe: The package is designed to be used safely in parallel environments. Internal locks (sync.Mutex) prevent race conditions when managing subscriptions and publishing events.
## Install
```bash
go get git.apihub24.de/admin/events
```
## Usage
```go
package main
import (
"fmt"
"sync"
"git.apihub24.de/admin/events"
)
// create some Events
const (
NameEventType events.EventType = "name"
GreetEventType events.EventType = "greet"
)
// and Event Data
type (
NameEventData struct {
Name string
}
GreetEventData struct {
Greeting string
}
)
// use handler to subscribe and publish
func main() {
handler := events.NewEventHandler()
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
nameSubscription := handler.Subscribe(NameEventType, func(event events.IEvent) {
// read the Name Event Data
var data NameEventData
_ = event.Data(&data)
// Publish the Greet Event
_ = handler.Publish(events.NewEvent(GreetEventType, GreetEventData{Greeting: fmt.Sprintf("Hello, %s", data.Name)}))
})
greetSubscription := handler.Subscribe(GreetEventType, func(event events.IEvent) {
var data GreetEventData
_ = event.Data(&data)
})
// publish the Name Event
_ = handler.Publish(nameEvent)
// unsubscribe Events
nameSubscription.Unsubscribe()
greetSubscription.Unsubscribe()
}
```

55
event.go Normal file
View File

@ -0,0 +1,55 @@
package events
import (
"fmt"
"reflect"
)
type EventType = string
type IEvent interface {
Typ() EventType
Data(ref any) error
}
func NewEvent[T any](typ EventType, data ...T) IEvent {
var d T
if len(data) > 0 {
d = data[0]
}
ev := &event[T]{
typ: typ,
data: d,
}
return ev
}
type event[T any] struct {
typ EventType
data T
}
func (event *event[T]) Typ() EventType {
return event.typ
}
func (event *event[T]) Data(ref any) error {
val := reflect.ValueOf(ref)
if val.Kind() != reflect.Ptr {
return fmt.Errorf("need Pointer to get Event Data")
}
valElem := val.Elem()
if !valElem.CanSet() {
return fmt.Errorf("cannot set value of the provided pointer")
}
dataType := reflect.TypeOf(event.data)
if valElem.Type() != dataType {
return fmt.Errorf("type mismatch: expected %s, got %s", dataType.String(), valElem.Type().String())
}
valElem.Set(reflect.ValueOf(event.data))
return nil
}

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module git.apihub24.de/admin/events
go 1.25.0
require github.com/google/uuid v1.6.0

2
go.sum Normal file
View File

@ -0,0 +1,2 @@
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=

56
handler.go Normal file
View File

@ -0,0 +1,56 @@
package events
import (
"sync"
"github.com/google/uuid"
)
type IEventHandler interface {
Publish(event IEvent) error
Subscribe(event EventType, handle func(event IEvent)) ISubscription
}
func NewEventHandler() IEventHandler {
handler := &eventHandler{
subscribers: make(map[EventType]map[string]func(IEvent)),
mu: sync.Mutex{},
}
return handler
}
type eventHandler struct {
subscribers map[EventType]map[string]func(IEvent)
mu sync.Mutex
}
func (handler *eventHandler) Publish(event IEvent) error {
for eventType, handles := range handler.subscribers {
if event.Typ() == eventType {
for _, handle := range handles {
handle(event)
}
}
}
return nil
}
func (handler *eventHandler) Subscribe(eventType EventType, handle func(event IEvent)) ISubscription {
handler.mu.Lock()
defer handler.mu.Unlock()
id := uuid.NewString()
if handler.subscribers[eventType] == nil {
handler.subscribers[eventType] = make(map[string]func(IEvent))
}
handler.subscribers[eventType][id] = handle
return newSubscription(func() {
handler.mu.Lock()
defer handler.mu.Unlock()
delete(handler.subscribers[eventType], id)
if len(handler.subscribers[eventType]) < 1 {
delete(handler.subscribers, eventType)
}
})
}

2
makefile Normal file
View File

@ -0,0 +1,2 @@
test:
- go test ./...

20
subscription.go Normal file
View File

@ -0,0 +1,20 @@
package events
type ISubscription interface {
Unsubscribe()
}
func newSubscription(remove func()) ISubscription {
sub := &subscription{
remove: remove,
}
return sub
}
type subscription struct {
remove func()
}
func (sub *subscription) Unsubscribe() {
sub.remove()
}

25
test/event_test.go Normal file
View File

@ -0,0 +1,25 @@
package events_test
import (
"testing"
"git.apihub24.de/admin/events"
)
func Test_Event_Data_ShouldGetErrorOnNoPointer(t *testing.T) {
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
var data NameEventData
err := nameEvent.Data(data)
if err == nil || err.Error() != "need Pointer to get Event Data" {
t.Errorf("expect error 'need Pointer to get Event Data'")
}
}
func Test_Event_Data_ShouldGetErrorOnTypeMissmatch(t *testing.T) {
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
var data GreetEventData
err := nameEvent.Data(&data)
if err == nil || err.Error() != "type mismatch: expected events_test.NameEventData, got events_test.GreetEventData" {
t.Errorf("expect error 'type mismatch: expected events_test.NameEventData, got events_test.GreetEventData'")
}
}

60
test/handler_test.go Normal file
View File

@ -0,0 +1,60 @@
package events_test
import (
"fmt"
"sync"
"testing"
"git.apihub24.de/admin/events"
)
const (
NameEventType events.EventType = "name"
GreetEventType events.EventType = "greet"
)
type (
NameEventData struct {
Name string
}
GreetEventData struct {
Greeting string
}
)
func Test_EventHandler_ShouldHandleSubscriptions(t *testing.T) {
handler := events.NewEventHandler()
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
wg := sync.WaitGroup{}
wg.Add(2)
handler.Subscribe(NameEventType, func(event events.IEvent) {
var data NameEventData
err := event.Data(&data)
if err != nil {
t.Error(err)
}
err = handler.Publish(events.NewEvent(GreetEventType, GreetEventData{Greeting: fmt.Sprintf("Hello, %s", data.Name)}))
if err != nil {
t.Error(err)
}
wg.Done()
})
handler.Subscribe(GreetEventType, func(event events.IEvent) {
var data GreetEventData
err := event.Data(&data)
if err != nil {
t.Error(err)
}
if data.Greeting != "Hello, Tom" {
t.Errorf("expect greeting 'Hello, Tom' but get '%s'", data.Greeting)
}
wg.Done()
})
err := handler.Publish(nameEvent)
if err != nil {
t.Error(err)
}
wg.Wait()
}

20
test/subscription_test.go Normal file
View File

@ -0,0 +1,20 @@
package events_test
import (
"testing"
"git.apihub24.de/admin/events"
)
func Test_Subscription_ShouldUnsubscribe(t *testing.T) {
handler := events.NewEventHandler()
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
handler.Subscribe(NameEventType, func(event events.IEvent) {
t.Errorf("expect not to execute unsubscribed Subscription")
}).Unsubscribe()
err := handler.Publish(nameEvent)
if err != nil {
t.Error(err)
}
}