example_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package pubsub_test
  15. import (
  16. "io/ioutil"
  17. "log"
  18. "testing"
  19. "golang.org/x/net/context"
  20. "golang.org/x/oauth2"
  21. "golang.org/x/oauth2/google"
  22. "google.golang.org/cloud"
  23. "google.golang.org/cloud/pubsub"
  24. )
  25. // TODO(jbd): Remove after Go 1.4.
  26. // Related to https://codereview.appspot.com/107320046
  27. func TestA(t *testing.T) {}
  28. func Example_auth() context.Context {
  29. // Initialize an authorized context with Google Developers Console
  30. // JSON key. Read the google package examples to learn more about
  31. // different authorization flows you can use.
  32. // http://godoc.org/golang.org/x/oauth2/google
  33. jsonKey, err := ioutil.ReadFile("/path/to/json/keyfile.json")
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. conf, err := google.JWTConfigFromJSON(
  38. jsonKey,
  39. pubsub.ScopeCloudPlatform,
  40. pubsub.ScopePubSub,
  41. )
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. ctx := cloud.NewContext("project-id", conf.Client(oauth2.NoContext))
  46. // See the other samples to learn how to use the context.
  47. return ctx
  48. }
  49. func ExamplePublish() {
  50. ctx := Example_auth()
  51. msgIDs, err := pubsub.Publish(ctx, "topic1", &pubsub.Message{
  52. Data: []byte("hello world"),
  53. })
  54. if err != nil {
  55. log.Fatal(err)
  56. }
  57. log.Printf("Published a message with a message id: %s\n", msgIDs[0])
  58. }
  59. func ExamplePull() {
  60. ctx := Example_auth()
  61. // E.g. c.CreateSub("sub1", "topic1", time.Duration(0), "")
  62. msgs, err := pubsub.Pull(ctx, "sub1", 1)
  63. if err != nil {
  64. log.Fatal(err)
  65. }
  66. log.Printf("New message arrived: %v\n", msgs[0])
  67. if err := pubsub.Ack(ctx, "sub1", msgs[0].AckID); err != nil {
  68. log.Fatal(err)
  69. }
  70. log.Println("Acknowledged message")
  71. }