Skip to content

Instantly share code, notes, and snippets.

@sugamon
Created December 24, 2019 02:35
Show Gist options
  • Save sugamon/34e8bcb0c54250ad7b458d5c7b0a878f to your computer and use it in GitHub Desktop.
Save sugamon/34e8bcb0c54250ad7b458d5c7b0a878f to your computer and use it in GitHub Desktop.
subscriber sample
package pubsub
import (
"context"
"fmt"
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
)
type Subscriber struct {
client *pubsub.Client
}
func NewSubscriber(ctx context.Context, projectID string, opts ...option.ClientOption) (*Subscriber, error) {
client, err := pubsub.NewClient(ctx, projectID, opts...)
if err != nil {
return nil, err
}
return &Subscriber{
client: client,
}, nil
}
func (s *Subscriber) Receive(ctx context.Context, subID string) error {
cctx, cancel := context.WithCancel(ctx)
sub := s.client.Subscription(subID)
err := sub.Receive(cctx, func(ctx context.Context, m *pubsub.Message) {
fmt.Printf("Got message: %s\n", m.Data)
m.Ack()
cancel()
})
if err != context.Canceled {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment