https://github.com/lestrrat-go/pubsub
Simple broadcast pattern
https://github.com/lestrrat-go/pubsub
Last synced: 4 months ago
JSON representation
Simple broadcast pattern
- Host: GitHub
- URL: https://github.com/lestrrat-go/pubsub
- Owner: lestrrat-go
- License: mit
- Created: 2022-02-08T06:55:00.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-02-27T02:53:39.000Z (over 2 years ago)
- Last Synced: 2025-01-09T03:41:41.359Z (6 months ago)
- Language: Go
- Size: 41 KB
- Stars: 5
- Watchers: 1
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
pubsub
=========Simple pubsub framework for Go.
This is (should be, fingers crossed) safe to be used from multiple goroutines. Designed such that only one goroutine makes changes to the object structure
```go
var svc pubsub.Service// Create a Loopback object for in-memory broadcasting.
// You can create similar publishing mechanism for gRPC, or whatever.
l := pubsub.NewLoopback(&svc)var msgs []interface{}
// You can create your own subscriber, of course, but this
// is the built-in hack to allow closures (eek)
sub := pubsub.SubscribeFunc(func(v interface{}) {
msgs = append(msgs, v)
})// Subscribing before starting the main loop is safe
svc.Subscribe(sub)// Sending before starting the main loop is safe
l.Send(`Hello`)ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()// Start the main loop
go svc.Run(ctx)// Sending after starting the main loop.. is obviously safe.
l.Send(`World!`)// If you have another subscriber, you can add it here.
// It will only receive subsequent pubsub requests
// svc.Subscribe(sub2)
```