main.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 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 main contains a client which pulls messages from a subscription and prints them.
  15. package main
  16. import (
  17. "flag"
  18. "fmt"
  19. "log"
  20. "time"
  21. "golang.org/x/net/context"
  22. "google.golang.org/cloud/pubsub"
  23. )
  24. var (
  25. projID = flag.String("p", "", "The ID of your Google Cloud project.")
  26. subName = flag.String("s", "", "The name of the subscription to pull from")
  27. numConsume = flag.Int("n", 10, "The number of messages to consume")
  28. )
  29. func main() {
  30. flag.Parse()
  31. if *projID == "" {
  32. log.Fatal("-p is required")
  33. }
  34. if *subName == "" {
  35. log.Fatal("-s is required")
  36. }
  37. ctx := context.Background()
  38. client, err := pubsub.NewClient(ctx, *projID)
  39. if err != nil {
  40. log.Fatalf("creating pubsub client: %v", err)
  41. }
  42. sub := client.Subscription(*subName)
  43. it, err := sub.Pull(ctx, time.Hour)
  44. if err != nil {
  45. fmt.Printf("error constructing iterator: %v", err)
  46. return
  47. }
  48. for i := 0; i < *numConsume; i++ {
  49. m, err := it.Next(ctx)
  50. if err != nil {
  51. break
  52. }
  53. fmt.Printf("got message: %v\n", string(m.Data))
  54. m.Done(true)
  55. }
  56. it.Close()
  57. if err != nil {
  58. fmt.Printf("%v", err)
  59. }
  60. }