All Products
Document Center

IoT Platform:Use the Paho MQTT library for Go to connect a device to IoT Platform

Last Updated:Aug 29, 2023

This topic describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for Go to connect a device to IoT Platform and enable messaging.

Usage notes

In this topic, the permissions of a common user are used to perform all operations. If you want to perform specific operations that require administrator permissions, run the sudo command.


A product and a device are created in the IoT Platform console. A device certificate is obtained. The certificate information includes the ProductKey, DeviceName, and DeviceSecret. For more information, see the following topics:

Prepare a development environment

Install the Go language package.

  • On macOS, run the following command:

    brew install go
  • On Ubuntu, run the following command:

    sudo apt-get install golang-go
  • On Windows, download the installation package from the official Go website and install the Go language package.


    If you reside in the Chinese mainland, you must use a virtual private network (VPN) to access the Go official website.

Download the Paho MQTT library for Go

For information about the Paho project and the supported programming languages, see Eclipse Paho Downloads.

Run the following commands to download the Paho MQTT library for Go and the related dependencies:

go get
go get
go get

Connect a device to IoT Platform

  1. Download the MqttSign.go file that is provided by Alibaba Cloud. The file contains the source code that is required to obtain the MQTT connection parameters.

    The MqttSign.go file defines the function that is used to obtain the MQTT connection parameters. You must call this function to connect your device to IoT Platform.

    • Definition:

      type AuthInfo struct {
          password, username, mqttClientId string;
      func calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp string) AuthInfo;
    • Description:

      This function is used to obtain the following MQTT connection parameters: username, password, and mqttClientId.

    • Input parameters:






      The ProductKey of the product to which the device belongs. This parameter is used to identify the device in IoT Platform.



      The DeviceName of the device. This parameter is used to identify the device in IoT Platform.



      The DeviceSecret of the device. This parameter is used to identify the device in IoT Platform.



      The ID of the device. The ID can be up to 64 characters in length. We recommend that you use the MAC address or serial number (SN) of the device as the ID.



      The timestamp of the current time. Unit: milliseconds.

    • Output parameters:

      This function returns an AuthInfo structure. The structure contains the parameters that are described in the following table.






      The username that is used to establish the MQTT connection.



      The password that is used to establish the MQTT connection.



      The ID of the MQTT client.

  2. Add a program file that can connect a device to IoT Platform.

    To obtain MQTT connection parameters, you must write a program to call the function in the MqttSign.go file.

    This section describes how to develop the device and provides sample code.

    • Specify the device information.

      // set the device info, include product key, device name, and device secret
          var productKey string = "a1Zd7n5***"
          var deviceName string = "testdevice"
          var deviceSecret string = "UrwclDV33NaFSmk0JaBxNTqgSrJW****"
          // set timestamp, clientid, subscribe topic and publish topic
          var timeStamp string = "1528018257135"
          var clientId string = "192.168.****"
          var subTopic string = "/" + productKey + "/" + deviceName + "/user/get";
          var pubTopic string = "/" + productKey + "/" + deviceName + "/user/update";
    • Specify MQTT connection information.

      Call the calculate_sign() function in the MqttSign.go file. This function returns the username, password, and mqttClientId parameters based on the values of the clientId, productKey, deviceName, deviceSecret, and timeStamp input parameters. Then, add the result to the opts structure.

          // set the login broker url
          var raw_broker bytes.Buffer
          opts := MQTT.NewClientOptions().AddBroker(raw_broker.String());
          // calculate the login auth info, and set it into the connection options
          auth := calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp)
          opts.SetKeepAlive(60 * 2 * time.Second)
      • If you use a public instance of the old version, replace cn-shanghai in raw_broker.WriteString("") with the ID of the region in which your device resides. For more information about region IDs, see Supported regions.

      • If you use an Enterprise Edition instance or a public instance of the new version, replace raw_broker.String() in opts := MQTT.NewClientOptions().AddBroker(raw_broker.String()); with <MQTT endpoint>:1833. Example: opts := MQTT.NewClientOptions().AddBroker("iot-***");.

        For information about how to obtain MQTT endpoints, see View the endpoint of a public instance of the new version or an Enterprise Edition instance.

      For information about IoT Platform instances, see Overview of instances.

    • Call the Connect() function of the Paho MQTT library for Go to connect the device to IoT Platform.

          // create and start a client using the above ClientOptions
          c := MQTT.NewClient(opts)
          if token := c.Connect(); token.Wait() && token.Error() != nil {
          fmt.Print("Connect aliyun IoT Cloud Success\n");
    • Call the Publish() function to publish messages. You must specify a topic to which you want to publish messages and the payloads of the messages.

          // publish 5 messages to pubTopic("/a1Zd7n5****/deng/user/update")
          for i := 0; i < 5; i++ {
              fmt.Println("publish msg:", i)
              text := fmt.Sprintf("ABC #%d", i)
              token := c.Publish(pubTopic, 0, false, text)
              fmt.Println("publish msg: ", text)
              time.Sleep(2 * time.Second)

      For information about topics, see What is a topic?

    • Call the Subscribe() function to subscribe to the topic and receive messages from IoT Platform.

          // subscribe to subTopic("/a1Zd7n5***/deng/user/get") and request messages to be delivered
          if token := c.Subscribe(subTopic, 0, nil); token.Wait() && token.Error() != nil {
          fmt.Print("Subscribe topic " + subTopic + " success\n");

    For information about the communication methods among devices, servers, and IoT Platform, see Overview of communications among devices, IoT platform, and servers.

  3. Compile the project.

Sample code

You can use the sample code to connect the device to IoT Platform.

  1. Download and decompress the demo package.

    The following table describes the files in the aiot-go-demo package.




    This file contains the code that is used to obtain the MQTT connection parameters. When you execute the iot.go file, the calculate_sign() function is called to obtain the username, password, and mqttClientId parameters.


    This file contains the logic code that is used to connect a device to IoT Platform and enable communications.


    The root certificate of IoT Platform. This certificate is required to connect devices to IoT Platform.

  2. Replace the device information in the iot.go file with your device information.

    You can use tools such as Linux vi to modify the iot.go file.

    • Replace the values of the productKey, deviceName, and deviceSecret parameters with your device certificate information.

    • Optional. Configure the timeStamp and clientId parameters. You can replace the value of the clientId parameter with the MAC address or SN of your device.

      If you do not configure the two parameters, you can still connect to IoT Platform. However, we recommend that you replace the values of the parameters with actual values.

    • Modify the MQTT connection parameters that are used to connect the device to IoT Platform. For more information, see Step 2 in the "Connect a device to IoT Platform" section of this topic.

  3. Run the following command in Command Prompt to execute the iot.go file:

    go run iot.go MqttSign.go 

    After you execute the file, the following local logs are generated:

    Connect aliyun IoT Cloud Sucess
    Subscribe topic /a1Zd7n5****/testdevice/user/get success
    publish msg: 0
    publish msg:  ABC #0
    publish msg: 1
    publish msg:  ABC #1
    publish msg: 2
    publish msg:  ABC #2
    publish msg: 3
    publish msg:  ABC #3
    publish msg: 4
    publish msg:  ABC #4
    publish msg: 5
    publish msg:  ABC #5

    In the IoT Platform console, you can view the device status and logs.

    • Choose Devices > Devices. The Devices page shows that the device is in Online state.

    • Choose Maintenance > Device Log. Then, click the Cloud run log or Device local log tab to view logs. For more information, see IoT Platform logs and Local device logs.

Error codes

If a device fails to establish an MQTT connection to IoT Platform, you can troubleshoot the issue based on the error code. For more information, see Troubleshooting.