Created
February 5, 2018 11:50
-
-
Save hitsumabushi/7cf1fa45813208f314b29da84a3ff2cc to your computer and use it in GitHub Desktop.
Google Pub/Sub Publisher sample in Golang
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 main | |
import ( | |
"context" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"google.golang.org/api/option" | |
"golang.org/x/oauth2/google" | |
"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) | |
} | |
topic := c.Topic(topicName) | |
defer topic.Stop() | |
var results []*pubsub.PublishResult | |
r := topic.Publish(ctx, &pubsub.Message{ | |
Data: []byte("hello world"), | |
}) | |
results = append(results, r) | |
for _, r := range results { | |
id, err := r.Get(ctx) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("Published a message with a message ID: %s\n", id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment