message.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 pubsub
  15. import (
  16. "encoding/base64"
  17. raw "google.golang.org/api/pubsub/v1"
  18. )
  19. // Message represents a Pub/Sub message.
  20. type Message struct {
  21. // ID identifies this message.
  22. // This ID is assigned by the server and is populated for Messages obtained from a subscription.
  23. // It is otherwise ignored.
  24. ID string
  25. // Data is the actual data in the message.
  26. Data []byte
  27. // Attributes represents the key-value pairs the current message
  28. // is labelled with.
  29. Attributes map[string]string
  30. // AckID is the identifier to acknowledge this message.
  31. AckID string
  32. // TODO(mcgreevy): unexport AckID.
  33. // TODO(mcgreevy): add publish time.
  34. calledDone bool
  35. // The iterator that created this Message.
  36. it *Iterator
  37. }
  38. func toMessage(resp *raw.ReceivedMessage) (*Message, error) {
  39. if resp.Message == nil {
  40. return &Message{AckID: resp.AckId}, nil
  41. }
  42. data, err := base64.StdEncoding.DecodeString(resp.Message.Data)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &Message{
  47. AckID: resp.AckId,
  48. Data: data,
  49. Attributes: resp.Message.Attributes,
  50. ID: resp.Message.MessageId,
  51. }, nil
  52. }
  53. // Done completes the processing of a Message that was returned from an Iterator.
  54. // ack indicates whether the message should be acknowledged.
  55. // Client code must call Done when finished for each Message returned by an iterator.
  56. // Done may only be called on Messages returned by an iterator.
  57. // If message acknowledgement fails, the Message will be redelivered.
  58. // Calls to Done have no effect after the first call.
  59. func (m *Message) Done(ack bool) {
  60. if m.calledDone {
  61. return
  62. }
  63. m.calledDone = true
  64. m.it.done(m.AckID, ack)
  65. }