message.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright © 2021 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package hub
  16. import "encoding/json"
  17. // Message gets converted to/from JSON and sent in the body of pubsub messages.
  18. type Message struct {
  19. Message string
  20. SenderID string
  21. Annotations map[string]interface{}
  22. }
  23. type MessageOption func(cfg *Message) error
  24. // Apply applies the given options to the config, returning the first error
  25. // encountered (if any).
  26. func (m *Message) Apply(opts ...MessageOption) error {
  27. for _, opt := range opts {
  28. if opt == nil {
  29. continue
  30. }
  31. if err := opt(m); err != nil {
  32. return err
  33. }
  34. }
  35. return nil
  36. }
  37. func NewMessage(s string) *Message {
  38. return &Message{Message: s}
  39. }
  40. func (m *Message) Copy() *Message {
  41. copy := *m
  42. return &copy
  43. }
  44. func (m *Message) WithMessage(s string) *Message {
  45. copy := m.Copy()
  46. copy.Message = s
  47. return copy
  48. }
  49. func (m *Message) AnnotationsToObj(v interface{}) error {
  50. blob, err := json.Marshal(m.Annotations)
  51. if err != nil {
  52. return err
  53. }
  54. return json.Unmarshal(blob, v)
  55. }