message.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package hub
  14. import "encoding/json"
  15. // Message gets converted to/from JSON and sent in the body of pubsub messages.
  16. type Message struct {
  17. Message string
  18. SenderID string
  19. Annotations map[string]interface{}
  20. }
  21. type MessageOption func(cfg *Message) error
  22. // Apply applies the given options to the config, returning the first error
  23. // encountered (if any).
  24. func (m *Message) Apply(opts ...MessageOption) error {
  25. for _, opt := range opts {
  26. if opt == nil {
  27. continue
  28. }
  29. if err := opt(m); err != nil {
  30. return err
  31. }
  32. }
  33. return nil
  34. }
  35. func NewMessage(s string) *Message {
  36. return &Message{Message: s}
  37. }
  38. func (m *Message) Copy() *Message {
  39. copy := *m
  40. return &copy
  41. }
  42. func (m *Message) WithMessage(s string) *Message {
  43. copy := m.Copy()
  44. copy.Message = s
  45. return copy
  46. }
  47. func (m *Message) AnnotationsToObj(v interface{}) error {
  48. blob, err := json.Marshal(m.Annotations)
  49. if err != nil {
  50. return err
  51. }
  52. return json.Unmarshal(blob, v)
  53. }