Skip to content

Instantly share code, notes, and snippets.

@simonmorley
Created March 26, 2016 12:31
Show Gist options
  • Save simonmorley/d6cda33b4adacb0105c9 to your computer and use it in GitHub Desktop.
Save simonmorley/d6cda33b4adacb0105c9 to your computer and use it in GitHub Desktop.
google pubsub golang pull example
package main
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/cloud"
"google.golang.org/cloud/pubsub"
"io/ioutil"
"log"
)
func main() {
jsonKey, err := ioutil.ReadFile("pubsub-key.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(
jsonKey,
pubsub.ScopeCloudPlatform,
pubsub.ScopePubSub,
)
if err != nil {
log.Fatal(err)
}
ctx := cloud.NewContext("xxx", conf.Client(oauth2.NoContext))
msgIDs, err := pubsub.Publish(ctx, "topic1", &pubsub.Message{
Data: []byte("hello world"),
})
if err != nil {
log.Println(err)
}
log.Printf("Published a message with a message id: %s\n", msgIDs[0])
for {
msgs, err := pubsub.Pull(ctx, "subscription1", 1)
if err != nil {
log.Println(err)
}
if len(msgs) > 0 {
log.Printf("New message arrived: %v, len: %d\n", msgs[0].ID, len(msgs))
if err := pubsub.Ack(ctx, "subscription1", msgs[0].AckID); err != nil {
log.Fatal(err)
}
log.Println("Acknowledged message")
log.Printf("Message: %s", msgs[0].Data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment