Created
July 27, 2016 19:35
-
-
Save frodopwns/399e0a5916dda30ef6a1d993354c95d3 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/google" | |
"google.golang.org/cloud" | |
"google.golang.org/cloud/pubsub" | |
) | |
const ( | |
projectID = "ecorson-drud" | |
jwtPath = "/path/to/your/jwt.json" | |
topicName = "topic_test" | |
subName = "topic_test" | |
numMsgs = 5 | |
) | |
func main() { | |
// read contents of jwt file | |
jbytes, err := ioutil.ReadFile(jwtPath) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
// instantiate googel conf using jwt contents | |
conf, err := google.JWTConfigFromJSON( | |
jbytes, | |
pubsub.ScopeCloudPlatform, | |
pubsub.ScopePubSub, | |
) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
// create a google cloud context | |
googleCTX := cloud.NewContext(projectID, conf.Client(oauth2.NoContext)) | |
// instantiate a client for workign with pub sub | |
client, err := pubsub.NewClient(googleCTX, projectID, cloud.WithTokenSource(conf.TokenSource(googleCTX))) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
// get topic, create it if it does not exist | |
exists, err := pubsub.TopicExists(googleCTX, topicName) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
var topic *pubsub.Topic | |
if exists { | |
topic = client.Topic(topicName) | |
} else { | |
topic, err = client.NewTopic(googleCTX, topicName) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
} | |
// publish 5 messages to the topic | |
for i := range []int{1, 2, 3, 4, 5} { | |
atts := map[string]string{ | |
"channel": "kube-alerts", | |
} | |
if i == 2 { | |
atts["severity"] = "warn" | |
} else if i == 3 { | |
atts["severity"] = "debug" | |
} else if i == 4 { | |
atts["severity"] = "fatal" | |
} else { | |
atts["severity"] = "good" | |
} | |
msgID, err := topic.Publish(googleCTX, &pubsub.Message{ | |
Data: []byte(fmt.Sprintf("message %d", i)), | |
Attributes: atts, | |
}) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
log.Println("New message id:", msgID) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment