tencent cloud

TDMQ for MQTT

Release Notes and Announcements
Release Notes
Product Introduction
TDMQ Product Series Introduction and Selection
What Is TDMQ for MQTT
Scenarios
Technical Architecture
Product series
MQTT Protocol Compatibility Notes
Comparison with Apache
High Availability
Product Constraints and Usage Quota
Basic Concepts
Supported Regions
Billing
Billing Overview
Renewal Instructions
Viewing Consumption Details
Overdue Payment Instructions
Refund
Getting Started
Guide for Getting Started
Preparations
Public Network Access
VPC Network Access
User Guide
Usage Process Guide
Configuring Account Permission
Creating a Cluster
Managing Topic
Connecting to the Cluster
Querying Messages
Managing Client
Managing a Cluster
Viewing Monitoring Metrics and Configuring Alarm Policies
Data Integration
Integrating Data Into SCF
Integrating Data Into CKafka
Integrating Data into RocketMQ
Development Guide
MQTT 5 Advanced Features
Data Plane HTTP API Description
Quota and Flow Control Mechanism Description
Configuring a Custom Domain Name
Configuring SQL Filtering
Configuring Point-to-Point Subscription
MQTT over QUIC
Managing Client Subscription
Message Enhancement Rule
Use Cases
Must-Knows for MQTT Client Development
Observability
Topic and Wildcard Subscriptions
​​API Reference
History
Introduction
API Category
Making API Requests
Cluster APIs
Topic APIs
Authorization Policy APIs
User APIs
Client APIs
Message Enhancement Rule APIs
Message APIs
Data Types
Error Codes
SDK Reference
Access Point Format
Java SDK
C SDK
Javascript/Node.JS/Mini Program
Go SDK
iOS SDK
JavaScript SDK
Dart SDK
Python SDK
.NET
Security and Compliance
Permission Management
FAQs
Related Agreement
Privacy Policy
Data Privacy And Security Agreement
TDMQ for MQTT Service Level Agreement
Contact Us

Go SDK

Focus Mode
Font Size
Last updated: 2026-04-01 16:37:51

Feature Overview

Eclipse Paho MQTT Go Client is a Go client library under the Eclipse Paho project. It can connect to an MQTT broker to publish messages, subscribe to topics and receive published messages, supporting a completely asynchronous operation mode.

Cloud Resource Preparation

Please refer to the operation step of creating a resource to complete cloud resource preparation.

Environment Preparation

Install Eclipse Paho SDK
MQTT 5.0
MQTT 3.1.1
go get github.com/eclipse/paho.golang

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

Sample Code

MQTT 5.0
MQTT 3.1.1
package main

import (
"context"
"fmt"
"net/url"
"os"
"os/signal"
"strconv"
"syscall"
"time"

"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
)

// Access point, obtained from the console
const accessPoint = "mqtt://mqtt-xxx-sh-public.mqtt.tencenttdmq.com:1883"

// Change this to something random if using a public test server
const clientID = "PahoGoClient"

const topic = "PahoGoTestTopic"

// User name, obtained from the console
const username = "YOUR_USERNAME"

// Password, obtained from the console
var password = []byte("YOUR_PASSWORD")

func main() {
// App will run until cancelled by user (e.g. ctrl-c)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

// We will connect to the Eclipse test server (note that you may see messages that other users publish)
u, err := url.Parse(accessPoint)
if err != nil {
panic(err)
}

cliCfg := autopaho.ClientConfig{
ServerUrls: []*url.URL{u},
ConnectUsername: username,
ConnectPassword: password,

// Keepalive message should be sent every 60 seconds
KeepAlive: 60,

// CleanStartOnInitialConnection defaults to false. Setting this to true will clear the session on the first connection.
CleanStartOnInitialConnection: false,

// SessionExpiryInterval - Seconds that a session will survive after disconnection.
// It is important to set this because otherwise, any queued messages will be lost if the connection drops and
// the server will not queue messages while it is down. The specific setting will depend upon your needs
// (60 = 1 minute, 3600 = 1 hour, 86400 = one day, 259200 = 3 days)
// MQTT server permits expiry interval up to 3 days
SessionExpiryInterval: 60,
OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
fmt.Println("mqtt connection up")
// Subscribing in the OnConnectionUp callback is recommended (ensures the subscription is reestablished if
// the connection drops)
if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{
Subscriptions: []paho.SubscribeOptions{
{Topic: topic, QoS: 1},
},
}); err != nil {
fmt.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
}
fmt.Println("mqtt subscription made")
},
OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\\n", err) },
// eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
ClientConfig: paho.ClientConfig{
// If you are using QOS 1/2, then it's important to specify a client id (which must be unique)
ClientID: clientID,
// OnPublishReceived is a slice of functions that will be called when a message is received.
// You can write the function(s) yourself or use the supplied Router
OnPublishReceived: []func(paho.PublishReceived) (bool, error){
func(pr paho.PublishReceived) (bool, error) {
fmt.Printf("received message on topic %s; body: %s (retain: %t)\\n", pr.Packet.Topic, pr.Packet.Payload, pr.Packet.Retain)
return true, nil
}},
OnClientError: func(err error) { fmt.Printf("client error: %s\\n", err) },
OnServerDisconnect: func(d *paho.Disconnect) {
if d.Properties != nil {
fmt.Printf("server requested disconnect: %s\\n", d.Properties.ReasonString)
} else {
fmt.Printf("server requested disconnect; reason code: %d\\n", d.ReasonCode)
}
},
},
}

c, err := autopaho.NewConnection(ctx, cliCfg) // starts process; will reconnect until context cancelled
if err != nil {
panic(err)
}
// Wait for the connection to come up
if err = c.AwaitConnection(ctx); err != nil {
panic(err)
}

ticker := time.NewTicker(time.Second)
msgCount := 0
defer ticker.Stop()
for {
select {
case <-ticker.C:
msgCount++
// Publish a test message (use PublishViaQueue if you don't want to wait for a response)
if _, err = c.Publish(ctx, &paho.Publish{
QoS: 1,
Topic: topic,
Payload: []byte("TestMessage: " + strconv.Itoa(msgCount)),
}); err != nil {
if ctx.Err() == nil {
panic(err) // Publish will exit when context cancelled or if something went wrong
}
}
continue
case <-ctx.Done():
}
break
}

fmt.Println("signal caught - exiting")
<-c.Done() // Wait for clean shutdown (cancelling the context triggered the shutdown)
}

package main

import (
"fmt"
"log"
"os"
"time"

mqtt "github.com/eclipse/paho.mqtt.golang"
)
// Cluster access point, obtained from the console
const accessPoint = "mqtt-xxx-sh-public.mqtt.tencenttdmq.com:1883"

// User name, obtained from the console
const username = "your-username"

// Password, obtained from the console
const password = "your-password"

// Client ID, must be unique in the cluster, usually product serial number, vehicle VIN code, and so on
const clientId = "VIN0001"

// Topic name of the message sent
const topic = "testtopic/1"

// Subscription expression
const topicFilter = "testtopic/#"

// Send and subscribe to QoS
const qos = 1

var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Println("Received a message:")
fmt.Printf("TOPIC: %s\\n", msg.Topic())
fmt.Printf("MSG: %s\\n", msg.Payload())
}

func main() {
mqtt.DEBUG = log.New(os.Stdout, "", 0)
mqtt.ERROR = log.New(os.Stdout, "", 0)
opts := mqtt.NewClientOptions().AddBroker(accessPoint).SetClientID(clientId)

opts.SetKeepAlive(60 * time.Second)
opts.SetUsername(username)
opts.SetPassword(password)

// Set message callback function
opts.SetDefaultPublishHandler(f)
opts.SetPingTimeout(1 * time.Second)

c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}

// Subscribe to a topic.
if token := c.Subscribe(topicFilter, qos, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}

// Publish a message.
token := c.Publish(topic, qos, false, "Hello World")
token.Wait()

time.Sleep(6 * time.Second)

// Unsubscribe
if token := c.Unsubscribe(topicFilter); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}

// Disconnect
c.Disconnect(250)
time.Sleep(1 * time.Second)
}



Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback