From d226bdf2d45f3500a3bda77dcac769b5eb5c9841 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Sat, 18 Mar 2017 19:00:11 +0000 Subject: [PATCH] Syntactic sugar for pubsub --- go-micro.go | 23 +++++++++++++++++++++++ publisher.go | 15 +++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 publisher.go diff --git a/go-micro.go b/go-micro.go index a72b6dd9..dd982100 100644 --- a/go-micro.go +++ b/go-micro.go @@ -22,6 +22,11 @@ type Service interface { String() string } +// Publisher is syntactic sugar for publishing +type Publisher interface { + Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error +} + type Option func(*Options) var ( @@ -43,3 +48,21 @@ func FromContext(ctx context.Context) (Service, bool) { func NewContext(ctx context.Context, s Service) context.Context { return context.WithValue(ctx, serviceKey{}, s) } + +// NewPublisher returns a new Publisher +func NewPublisher(topic string, c client.Client) Publisher { + if c == nil { + c = client.NewClient() + } + return &publisher{c, topic} +} + +// RegisterHandler is syntactic sugar for registering a handler +func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error { + return s.Handle(s.NewHandler(h, opts...)) +} + +// RegisterSubscriber is syntactic sugar for registering a subscriber +func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error { + return s.Subscribe(s.NewSubscriber(topic, h)) +} diff --git a/publisher.go b/publisher.go new file mode 100644 index 00000000..f6979021 --- /dev/null +++ b/publisher.go @@ -0,0 +1,15 @@ +package micro + +import ( + "github.com/micro/go-micro/client" + "golang.org/x/net/context" +) + +type publisher struct { + c client.Client + topic string +} + +func (p *publisher) Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error { + return p.c.Publish(ctx, p.c.NewPublication(p.topic, msg)) +}