All Products
Search
Document Center

IoT Platform:Connect a device to IoT Platform by using Paho MQTT for Go

Last Updated:Jun 03, 2026

Connect a device to Alibaba Cloud IoT Platform and exchange messages by using the Paho MQTT library for Go.

Usage notes

All operations in this topic use common user permissions. Run the sudo command if an operation requires administrator permissions.

Prerequisites

A product and a device are created in the IoT Platform console, and device certificate information (ProductKey, DeviceName, and DeviceSecret) is obtained. Setup instructions:

Prepare the development environment

Install Go:

  • On macOS, run the following command:

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

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

    Note

    Users in the Chinese mainland require a VPN to access the official Go website.

Download the Paho MQTT library for Go

The Paho project supports multiple programming languages. Download links are available on Eclipse Paho Downloads.

Run the following commands to install the Paho MQTT library and dependencies:

go get github.com/eclipse/paho.mqtt.golang
go get github.com/gorilla/websocket
go get golang.org/x/net/proxy

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 a function that generates MQTT connection parameters. 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:

      Returns the MQTT connection parameters: username, password, and mqttClientId.

    • Input parameters:

      Parameter

      Type

      Description

      productKey

      String

      The ProductKey of the product to which the device belongs.

      deviceName

      String

      The DeviceName of the device.

      deviceSecret

      String

      The DeviceSecret of the device.

      clientId

      String

      The ID of the device. Up to 64 characters. We recommend that you use the MAC address or SN of the device.

      timeStamp

      String

      The timestamp of the current time. Unit: milliseconds.

    • Output parameters:

      This function returns an AuthInfo structure with the following fields:

      Parameter

      Type

      Description

      username

      String

      The username for the MQTT connection.

      password

      String

      The password for the MQTT connection.

      mqttClientId

      String

      The ID of the MQTT client.

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

    Write a program that calls the function in MqttSign.go to obtain the MQTT connection parameters.

    The following sections describe how to develop the device program with 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 calculate_sign() in MqttSign.go. This function returns the username, password, and mqttClientId parameters based on the clientId, productKey, deviceName, deviceSecret, and timeStamp inputs. Add the result to the opts structure.

          // set the login broker url
          var raw_broker bytes.Buffer
          raw_broker.WriteString("tls://")
          raw_broker.WriteString(productKey)
          raw_broker.WriteString(".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883")
          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.SetClientID(auth.mqttClientId)
          opts.SetUsername(auth.username)
          opts.SetPassword(auth.password)
          opts.SetKeepAlive(60 * 2 * time.Second)
          opts.SetDefaultPublishHandler(f)
      Important
      • If you use a public instance of the old version, replace cn-shanghai in raw_broker.WriteString(".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883") with the ID of the region in which your device resides. For information about region IDs, see Region list.

      • 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-***.mqtt.iothub.aliyuncs.com:1883");.

        For information about how to obtain MQTT endpoints, see View endpoints for public and Enterprise Edition instances.

      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 {
              panic(token.Error())
          }
          fmt.Print("Connect aliyun IoT Cloud Success\n");
    • Call Publish() to publish messages. Specify the target topic and message payload.

          // 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)
              token.Wait()
              time.Sleep(2 * time.Second)
          }

      Learn about topics in What is a topic?

    • Call Subscribe() to subscribe to a 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.Println(token.Error())
              os.Exit(1)
          }
          fmt.Print("Subscribe topic " + subTopic + " success\n");
                                      

    Learn about device-cloud communication patterns in Overview of communications among devices, IoT platform, and servers.

  3. Compile the project.

Sample code

Connect a device to IoT Platform by using the sample code.

  1. Download and decompress the demo package.

    The aiot-go-demo package contains the following files:

    File

    Description

    MqttSign.go

    Contains the code for generating MQTT connection parameters. When iot.go runs, it calls calculate_sign() to obtain username, password, and mqttClientId.

    iot.go

    Contains the logic for connecting a device to IoT Platform and enabling communication.

    x509

    The root certificate of IoT Platform, required for device connections.

    Note

    If you connect a device to IoT Platform by using an MQTT cloud gateway, you can use a custom certificate to verify the device identity. For more information, see Step 1: Generate custom certificates.

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

    Use a text editor 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.

      These parameters are optional for connectivity, but we recommend that you set them to 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 execution, the following local logs are generated:

    clientId192.168.****deviceNametestdeviceproductKeya1Zd7n5****timestamp1528018257135
    1b865320fc183cc747041c9faffc9055fc45****
    Connect aliyun IoT Cloud Success
    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

    Log in to the IoT Platform console. In your instance, you can view the device status and logs.

    • In the left-side navigation pane, choose Device Management > Devices. You can see that the device status is Online.

    • Choose Monitoring & O&M > Log Service. You can view IoT Platform logs and on-premises device logs. For more information, see IoT Platform logs and On-premises device logs.

Error codes

If the device fails to connect to IoT Platform over MQTT, use the error codes to troubleshoot the issue. For more information about server-side error codes, see Troubleshooting.