Created
January 11, 2020 05:43
-
-
Save sugamon/7326f986235761e34cd66ee40cdb25cd to your computer and use it in GitHub Desktop.
pubsub apiv1 publisher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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