sensenet/receiver/receiver.go

61 lines
1020 B
Go
Raw Normal View History

2022-02-27 06:57:13 +00:00
package receiver
import (
"log"
"git.wntrmute.dev/kyle/sensenet/config"
"git.wntrmute.dev/kyle/sensenet/pubsub"
"git.wntrmute.dev/kyle/sensenet/topic"
)
const (
packetBuffer = 64
errBuffer = 64
)
type Receiver struct {
packets chan *topic.Packet
errs chan error
}
func receive(packets chan *topic.Packet, errs chan error, subscriber *pubsub.Subscriber) {
packet, err := subscriber.Receive()
if err != nil {
errs <- err
return
}
packets <- packet
}
func (rcvr *Receiver) Subscribe(addr string, publisher *config.Publisher) error {
subscriber, err := pubsub.NewSubscriber(addr, publisher.Name, publisher.Topics...)
if err != nil {
return err
}
go func() {
for {
receive(rcvr.packets, rcvr.errs, subscriber)
}
}()
return nil
}
func (rcvr *Receiver) LogErrors() {
for {
select {
case err := <-rcvr.errs:
log.Println(err)
}
}
}
func New() *Receiver {
return &Receiver{
packets: make(chan *topic.Packet, packetBuffer),
errs: make(chan error, errBuffer),
}
}