natsio/pubsub.go

33 lines
758 B
Go
Raw Normal View History

2021-10-08 04:23:59 +00:00
package natsio
import (
"errors"
"fmt"
"github.com/nats-io/nats.go"
)
// Publish ...
func Publish(stream, subject string, payload []byte) error {
2021-10-08 07:41:58 +00:00
channel := combineStreamAndSubjectName(stream, subject)
_, err := natsJS.PublishAsync(channel, payload)
2021-10-08 04:23:59 +00:00
if err != nil {
2021-10-08 07:41:58 +00:00
msg := fmt.Sprintf("publish message to subject %s error: %s", channel, err.Error())
2021-10-08 04:23:59 +00:00
return errors.New(msg)
}
return nil
}
// Subscribe ...
2021-10-13 07:53:16 +00:00
func Subscribe(stream, subject string, cb nats.MsgHandler) (*nats.Subscription, error) {
2021-10-08 07:41:58 +00:00
channel := combineStreamAndSubjectName(stream, subject)
2021-10-13 07:53:16 +00:00
sub, err := natsJS.Subscribe(channel, cb)
2021-10-08 04:23:59 +00:00
if err != nil {
2021-10-08 07:41:58 +00:00
msg := fmt.Sprintf("subscribe subject %s error: %s", channel, err.Error())
2021-10-13 07:53:16 +00:00
return nil, errors.New(msg)
2021-10-08 04:23:59 +00:00
}
2021-10-13 07:53:16 +00:00
return sub, nil
2021-10-08 04:23:59 +00:00
}