Skip to content

Instantly share code, notes, and snippets.

@sugamon
Created January 11, 2020 05:43
Show Gist options
  • Save sugamon/7326f986235761e34cd66ee40cdb25cd to your computer and use it in GitHub Desktop.
Save sugamon/7326f986235761e34cd66ee40cdb25cd to your computer and use it in GitHub Desktop.
pubsub apiv1 publisher
package pubsub
import (
"context"
pubsub "cloud.google.com/go/pubsub/apiv1"
"google.golang.org/api/option"
pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1"
)
type Publisher struct {
Client *pubsub.PublisherClient
}
func NewPublisher(ctx context.Context, opts ...option.ClientOption) (*Publisher, error) {
client, err := pubsub.NewPublisherClient(ctx, opts...)
if err != nil {
return nil, err
}
return &Publisher{
Client: client,
}, nil
}
func (p *Publisher) Publish(ctx context.Context, topic string, msg string) error {
pMsgs := make([]*pubsubpb.PubsubMessage, 0)
pMsgs = append(pMsgs, &pubsubpb.PubsubMessage{
Data: []byte(msg),
})
req := &pubsubpb.PublishRequest{
Topic: topic,
Messages: pMsgs,
}
_, err := p.Client.Publish(ctx, req)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment