Skip to content

Instantly share code, notes, and snippets.

@hitsumabushi
Created February 5, 2018 11:53
Show Gist options
  • Select an option

  • Save hitsumabushi/baaeefd241e27ab0414763bdc6a93f11 to your computer and use it in GitHub Desktop.

Select an option

Save hitsumabushi/baaeefd241e27ab0414763bdc6a93f11 to your computer and use it in GitHub Desktop.

Revisions

  1. hitsumabushi created this gist Feb 5, 2018.
    43 changes: 43 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    package main

    import (
    "context"
    "fmt"
    "io/ioutil"
    "log"

    "golang.org/x/oauth2/google"

    "google.golang.org/api/option"

    "cloud.google.com/go/pubsub"
    )

    const (
    credentialJSONPath = ""
    projectID = ""
    topicName = ""
    )

    func main() {
    jsonKey, err := ioutil.ReadFile(credentialJSONPath)
    conf, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub, pubsub.ScopeCloudPlatform)
    if err != nil {
    log.Fatal(err)
    }
    ctx := context.Background()
    ts := conf.TokenSource(ctx)
    c, err := pubsub.NewClient(ctx, projectID, option.WithTokenSource(ts))
    if err != nil {
    log.Fatal("new client:", err)
    }

    sub := c.Subscription(topicName)
    err = sub.Receive(context.Background(), func(ctx context.Context, m *pubsub.Message) {
    log.Printf("Got message: %s", m.Data)
    m.Ack()
    })
    if err != nil {
    log.Fatal("Receive:", err)
    }
    }