Created
December 24, 2019 02:35
-
-
Save sugamon/34e8bcb0c54250ad7b458d5c7b0a878f to your computer and use it in GitHub Desktop.
subscriber sample
This file contains hidden or 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" | |
"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