Connect via Go SDK

Eclipse Paho MQTT Go ClientConnect via Go SDK - 图1 (opens new window) is the Go language client library under the Eclipse Paho project, which can connect to the MQTT Broker to publish messages, subscribe to topics and receive the published message. It supports asynchronous operation mode completely.

The client depends on Google’s software Package of proxyConnect via Go SDK - 图2 (opens new window) and websocketsConnect via Go SDK - 图3 (opens new window), which can be installed with the following command:

  1. go get github.com/eclipse/paho.mqtt.golang

MQTT Go usage example

This example contains the complete code for Paho MQTT in Go language connecting to EMQX, sending and receiving messages:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "time"
  7. "github.com/eclipse/paho.mqtt.golang"
  8. )
  9. var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  10. fmt.Printf("TOPIC: %s\n", msg.Topic())
  11. fmt.Printf("MSG: %s\n", msg.Payload())
  12. }
  13. func main() {
  14. mqtt.DEBUG = log.New(os.Stdout, "", 0)
  15. mqtt.ERROR = log.New(os.Stdout, "", 0)
  16. opts := mqtt.NewClientOptions().AddBroker("tcp://broker.emqx.io:1883").SetClientID("emqx_test_client")
  17. opts.SetKeepAlive(60 * time.Second)
  18. // Set the message callback handler
  19. opts.SetDefaultPublishHandler(f)
  20. opts.SetPingTimeout(1 * time.Second)
  21. c := mqtt.NewClient(opts)
  22. if token := c.Connect(); token.Wait() && token.Error() != nil {
  23. panic(token.Error())
  24. }
  25. // Subscribe to a topic
  26. if token := c.Subscribe("testtopic/#", 0, nil); token.Wait() && token.Error() != nil {
  27. fmt.Println(token.Error())
  28. os.Exit(1)
  29. }
  30. // Publish a message
  31. token := c.Publish("testtopic/1", 0, false, "Hello World")
  32. token.Wait()
  33. time.Sleep(6 * time.Second)
  34. // Unscribe
  35. if token := c.Unsubscribe("testtopic/#"); token.Wait() && token.Error() != nil {
  36. fmt.Println(token.Error())
  37. os.Exit(1)
  38. }
  39. // Disconnect
  40. c.Disconnect(250)
  41. time.Sleep(1 * time.Second)
  42. }

Paho Golang MQTT 5.0 support

Currently, Paho Golang is still adapting to MQTT 5.0 and has not yet fully supported it.