publish.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package mqtt
  2. import (
  3. "context"
  4. "encoding/json"
  5. )
  6. // PublishOption are extra options when publishing a message
  7. type PublishOption int
  8. const (
  9. // Retain tells the broker to retain a message and send it as the first message to new subscribers.
  10. Retain PublishOption = iota
  11. )
  12. // Publish a message with a byte array payload
  13. func (c *Client) Publish(ctx context.Context, topic string, payload []byte, qos QOS, options ...PublishOption) error {
  14. return c.publish(ctx, topic, payload, qos, options)
  15. }
  16. // PublishString publishes a message with a string payload
  17. func (c *Client) PublishString(ctx context.Context, topic string, payload string, qos QOS, options ...PublishOption) error {
  18. return c.publish(ctx, topic, []byte(payload), qos, options)
  19. }
  20. // PublishJSON publishes a message with the payload encoded as JSON using encoding/json
  21. func (c *Client) PublishJSON(ctx context.Context, topic string, payload interface{}, qos QOS, options ...PublishOption) error {
  22. data, err := json.Marshal(payload)
  23. if err != nil {
  24. return err
  25. }
  26. return c.publish(ctx, topic, data, qos, options)
  27. }
  28. func (c *Client) publish(ctx context.Context, topic string, payload []byte, qos QOS, options []PublishOption) error {
  29. var retained = false
  30. for _, option := range options {
  31. switch option {
  32. case Retain:
  33. retained = true
  34. }
  35. }
  36. token := c.client.Publish(topic, byte(qos), retained, payload)
  37. return tokenWithContext(ctx, token)
  38. }