github.com/xmlking/toolkit/broker/pubsub@v0.3.4/broker.go (about)

     1  package broker
     2  
     3  import (
     4  	"context"
     5  
     6  	"cloud.google.com/go/pubsub"
     7  )
     8  
     9  // Broker is an interface used for asynchronous messaging.
    10  type Broker interface {
    11  	NewPublisher(topic string, opts ...PublishOption) (pub Publisher, err error)
    12  	AddSubscriber(subscription string, hdlr Handler, opts ...SubscribeOption) (err error)
    13  	Start() error
    14  }
    15  
    16  type Publisher interface {
    17  	Publish(ctx context.Context, msg *pubsub.Message) error
    18  }
    19  
    20  // Handler is used to process messages via a subscription of a topic.
    21  // The handler is passed a publication interface which contains the
    22  // message and optional Ack method to acknowledge receipt of the message.
    23  type Handler func(context.Context, *pubsub.Message)
    24  
    25  var DefaultBroker Broker
    26  
    27  // NewBroker creates and returns a new Broker based on the packages within.
    28  func NewBroker(ctx context.Context, opts ...Option) Broker {
    29  	return newBroker(ctx, opts...)
    30  }
    31  
    32  func Start() error {
    33  	return DefaultBroker.Start()
    34  }
    35  
    36  func NewPublisher(topic string, opts ...PublishOption) (Publisher, error) {
    37  	return DefaultBroker.NewPublisher(topic, opts...)
    38  }
    39  
    40  func AddSubscriber(subscription string, handler Handler, opts ...SubscribeOption) error {
    41  	return DefaultBroker.AddSubscriber(subscription, handler, opts...)
    42  }