1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-11-24 08:02:32 +02:00

Syntactic sugar for pubsub

This commit is contained in:
Asim Aslam 2017-03-18 19:00:11 +00:00
parent 0c2c53e9af
commit d226bdf2d4
2 changed files with 38 additions and 0 deletions

View File

@ -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))
}

15
publisher.go Normal file
View File

@ -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))
}