
MQTT is a lightweight messaging protocol that's widely used in IoT and real-time data transmission. It's designed to be efficient and scalable, making it a great choice for large-scale applications.
The Go language has a built-in MQTT client library, which makes it easy to get started with MQTT development. This library provides a simple and intuitive API for connecting to MQTT brokers and publishing/subscribing to topics.
MQTT brokers act as intermediaries between publishers and subscribers, routing messages between them. You can choose from various MQTT broker implementations, such as Mosquitto or HiveMQ, depending on your needs.
Take a look at this: S Golang
Installation and Setup
To install the golang mqtt library, you're recommended to use modules. Using modules simplifies the installation process and ensures you have the latest packages.
If you're using modules, you can simply import "github.com/eclipse/paho.mqtt.golang" and the necessary packages will be downloaded automatically when you run go build. This makes it easy to get started with the library.
The client depends on Google's proxy package and the websockets package, which can be easily installed with a few commands.
Check this out: Create a Package in Golang
Discover more: Golang Wifi
Installation and Build

The process of installation and build depends on whether you're using modules (recommended) or GOPATH.
If you're using modules, you can simply import "github.com/eclipse/paho.mqtt.golang" and the necessary packages will be downloaded automatically when you run go build.
Note that the latest release will be downloaded and changes may have been made since the release. If you've encountered an issue, or wish to try the latest code for another reason, then run "go get github.com/eclipse/paho.mqtt.golang@master" to get the latest commit.
Installation is as easy as importing the necessary packages and running go build.
Additional reading: Simple Http Server Golang Github
Project Initialization
To initialize your project, you'll need to install the MQTT client library, paho.mqtt.golang. This library is essential for communicating with the MQTT broker.
You can install it by following the instructions provided.
You might enjoy: Azure Mqtt
MQTT Basics
MQTT is a lightweight messaging protocol based on the publish/subscribe model that is widely used in IoT and other applications where low bandwidth and low power consumption are important.
MQTT is used in applications where low bandwidth and low power consumption are crucial.
The popular MQTT library in Golang is paho.mqtt.golang.
This library is widely used for its efficiency and effectiveness in handling MQTT communications.
MQTT's publish/subscribe model allows for efficient communication between devices and applications.
This model enables devices to publish messages to a topic, and other devices or applications can subscribe to that topic to receive the messages.
The publish/subscribe model is a key feature of MQTT that makes it suitable for IoT and other applications.
Creating Applications
You can create an MQTT v3.1.1 client using the NewClient function, which requires a ClientOptions object to specify the connection settings.
Before the client is ready for use, you must call the Connect method on it to create resources such as a net connection.
The client is now set up and ready to be used for publishing and subscribing to topics.
MQTT Connection
To establish an MQTT connection, you can use the `ConnectMQTT` function, which takes a connected `net.Conn` and performs the initial MQTT handshake. This function is available since version 1.3.0.
The `ConnectMQTT` function has several parameters, including `conn`, `cm`, and `protocolVersion`. Note that it suppresses actual connection errors for backward compatibility.
To handle the connection state change, you can use the `OnConnectHandler` callback, which is set using the `SetOnConnectHandler` method. This callback is called both at initial connection time and upon automatic reconnect.
Here are the key details you need to know about the MQTT connection:
- Broker: The hostname or IP address of the MQTT broker.
- TCP Port: The port number used for MQTT communication over TCP.
- Topic: A form of addressing that allows MQTT clients to share information.
Access Details
To establish a connection with an MQTT broker, you need to know the hostname or IP address of the broker.
The TCP port number used for MQTT communication over TCP is crucial for the connection to work properly.
MQTT clients use a specific addressing system called a topic to share information.
To set up your MQTT connection, you'll need to have the following information:
- Broker: The hostname or IP address of the MQTT broker
- TCP Port: The port number used for MQTT communication over TCP
- Topic: A form of addressing that allows MQTT clients to share information.
Connect to Broker
To connect to an MQTT broker, you need a few essential components: ClientOptions, a message pub handler, a connect handler, and a connect lost handler. These components work together to ensure a smooth connection.
The ClientOptions are used to set the broker, port, client ID, username, password, and other options. You can also use this to set the client certificate if you're using a TSL connection.
The message pub handler is a global MQTT pub message processing function that helps with message publishing. The connect handler is a callback function that's triggered when the client connects to the broker. You can use this to perform any necessary actions when the connection is established.
If you're using a TSL connection, you'll need to set the client certificate. If it's not set, you can do so by following the instructions in the documentation.
Here are the essential details you need to know about connecting to an MQTT broker:
You can also specify the time to wait between connection attempts when initially connecting by using the SetConnectRetryInterval function. This is particularly useful if you're experiencing connection issues.
To add a broker URI to the list of brokers to be used, you can use the AddBroker function. This function takes a scheme, host, and port as arguments, and returns a broker URI in the format scheme://host:port. For example, you could use the following code to add a broker URI: tcp://foobar.com:1883.
Related reading: Golang Use Cases
ResumeSubs 1.2.0
ResumeSubs 1.2.0 is a game-changer for MQTT connections.
With the introduction of ResumeSubs in version 1.2.0, you can now enable resuming of stored (un)subscribe messages when connecting to an MQTT server.
This means you can pick up where you left off, even after a disconnect.
If you set CleanSession to false, these messages will be stored and resumed on connection. Otherwise, they're discarded.
ResumeSubs returns true if resuming stored (un)sub is enabled, giving you a simple way to check the status.
This feature is available in both the ClientOptions and ClientOptionsReader.
MQTT Configuration
MQTT Configuration is a crucial step in setting up a GoLang MQTT application.
You'll need to configure the MQTT broker, such as Mosquitto, to allow connections from your GoLang application.
The broker's address and port number are typically specified in the application's configuration file, as shown in the example of using the `github.com/eclipse/paho.mqtt.golang` package.
The default port number for Mosquitto is 1883, but you can change it if needed.
Options
When creating an MQTT client, it's essential to understand the options available to configure it properly. ClientOptions contains the configurable options for an MQTT client.
To set up these options, you can use the relevant methods, such as AddBroker, rather than directly modifying them. This approach helps avoid potential issues like those seen with Mosquitto 2.0.12+, which rejects connections with a KeepAlive value of 0.
Don't create ClientOptions directly unless you have a compelling reason to do so. Instead, use NewClientOptions to create a new ClientOptions type with some default values.
One option you can use is UnsetWill, which will cause any set will message to be disregarded. This can be useful in certain situations where you need to override a previously set will message.
The SetMessageChannelDepth option is actually deprecated and no longer has any effect, so you can ignore it.
Username
When setting up an MQTT client, it's essential to configure the username correctly.
The username is used by the client when connecting to the MQTT broker.
Note that without the use of SSL/TLS, the username information will be sent in plaintext across the wire.
This means that if you're not using encryption, your username will be visible to anyone intercepting your connection.
To set the username, you can use the SetUsername function, which is available in the ClientOptions struct.
Http Headers
In the context of MQTT configuration, HTTP headers play a crucial role in the WebSocket opening handshake.
The `SetHTTPHeaders` function, introduced in Inv1.2.0, allows you to set additional HTTP headers that will be sent in the WebSocket opening handshake.
This is particularly useful for customizing the handshake process to meet specific requirements.
Take a look at this: Websockets Go
MQTT Settings
You can configure MQTT settings using ClientOptions, which contains options for an MQTT client. Note that these options should be set using specific methods like AddBroker, rather than directly.
Create a new ClientOptions instance using NewClientOptions, unless you have a good reason not to. This is because creating a configuration with default values can make it easier to track issues.
The SetMessageChannelDepth function is deprecated and has no effect, so you can ignore it.
New Options
You can create a new MQTT client with specific options using the `NewClient` function. It's essential to call the `Connect` method on the client before using it, to ensure resources are created.
The `ClientOptions` type contains configurable options for a client, but be aware that setting these options directly can lead to difficult-to-trace issues. Instead, use the `AddBroker` method or create a new `ClientOptions` instance with `NewClientOptions`.
When creating a new `ClientOptions` instance, consider using `NewClientOptions` to get some default values. This can simplify the configuration process and reduce the risk of errors.
The `SetAutoAckDisabled` method allows you to enable or disable automated acknowledgment of messages received by the handler. This feature was added in version 1.4.2 of the library.
Clean Session in v1.1.0
Clean Session in v1.1.0 is a significant update that allows for a clean start in MQTT settings.
The CleanSession feature was added in version 1.1.0, which means it's a relatively recent addition to MQTT settings.
CleanSession returns whether Cleansession is set, giving you a clear indication of its status.
MQTT Error Handling
MQTT Error Handling is crucial when working with asynchronous libraries like golang mqtt. This library's nature makes it easy to forget to check for errors.
One way to handle errors is to use a goroutine to log them. This can help prevent errors from slipping through the cracks.
Forgetting to check for errors can lead to frustrating bugs that are hard to track down. It's essential to prioritize error handling in your code.
Using a goroutine to log errors is a simple and effective solution that can save you a lot of time and stress in the long run.
MQTT Security
Setting up credentials for your MQTT client is crucial for secure connections. You can use the SetCredentialsProvider function to set a method that provides the current username and password when connecting to the MQTT broker.
Without the use of SSL/TLS, this information will be sent in plaintext across the wire. This is a significant security risk that should be avoided.
CredentialsProvider Inv1.1.1

CredentialsProvider Inv1.1.1 is a method that sets a way for the client to get the current username and password when connecting to the MQTT broker.
This method is particularly useful for applications that need to authenticate users dynamically. Note: without the use of SSL/TLS, this information will be sent in plaintext across the wire.
Inv1.1.1 is a specific version of the CredentialsProvider method, indicating that it was added in version 1.1.1 of the client library.
Using CredentialsProvider Inv1.1.1 can provide a more flexible and secure way to handle user authentication, but it's essential to use SSL/TLS to protect the sensitive information being sent.
Without SSL/TLS, the username and password will be sent in plaintext, making it vulnerable to interception and eavesdropping.
Tls Config
Tls Config is an essential component of MQTT security. It allows you to set an SSL/TLS configuration to be used when connecting to an MQTT broker.
To set up Tls Config, you can use the SetTLSConfig function, which is part of the ClientOptions. This function will take care of the SSL/TLS configuration for you, so you don't need to worry about the details.
Reading the official Go documentation is recommended for more information on using SetTLSConfig.
Discover more: Golang Config
MQTT Messages
MQTT Messages are received messages that are passed to the callbacks, not internal messages. They define the externals that a message implementation must support.
A MessageHandler is a callback type which can be set to be executed upon the arrival of messages published to topics to which the client is subscribed. This callback function is used to handle incoming messages in an MQTT subscriber.
MQTT messages are identified by a 16-bit message id, known as MId, which should not be depended upon by the client application. This means that the client should not rely on the message id for any critical functionality.
What Is Topic?
A topic in MQTT is a way for clients to share information. It's structured like a file system, with levels separated by forward slashes (/).
MQTT topics are hierarchical, making it easy to organize and access data. This structure is similar to how we organize files on our computers.
For example, a topic like "test/demo" shows how levels are separated by a forward slash. This indicates that the topic is located under the "test" level, with "demo" being a sub-level.
Sample topics like "room/temperature" and "room/humidity" demonstrate how topics can be used to share specific types of data.
Message
A message in MQTT is defined by the externals that a message implementation must support, which are received messages that are passed to the callbacks, not internal messages.
These messages can be passed to the callbacks when a client is subscribed to a topic, thanks to the MessageHandler callback type. This type can be set to be executed upon the arrival of messages published to topics.
The MessageID is an important part of a message, as it returns the MQTT message ID that was assigned to the Publish packet when it was sent to the broker.
Here are some key things to know about MessageIDs:
The SubscribeToken is an extension of Token containing the extra fields required to provide information about calls to Subscribe(). This token can be used to get the result of a subscription, including a map of topics that were subscribed to along with the matching return code from the broker.
MQTT Connection Management
MQTT Connection Management is a crucial aspect of working with the GoLang MQTT library. You can set the maximum time to wait between reconnection attempts with the SetMaxReconnectInterval() function.
The library allows for flexible connection management, enabling you to set a connection timeout with the SetConnectTimeout() function. By default, this value is set to 30 seconds, but you can adjust it to suit your needs. This is particularly useful when working with unreliable network connections.
To handle connection losses, you can set a ConnectionLostHandler callback using the ConnectionLostHandler type. This callback will be executed when the connection is lost, allowing you to implement custom logic to handle the disconnection.
Connection Attempt Inv 1.3.4
With the introduction of Inv 1.3.4, connection attempts have become more manageable.
You can set a Connection Attempt Handler callback to be executed prior to each attempt to connect to an MQTT broker. This allows connection-specific changes to be made to the tls.Config.
The Connection Attempt Handler callback returns the *tls.Config that will be used when establishing the connection, along with the broker URL. This is useful for making connection-specific changes.
To set the Connection Attempt Handler, use the SetConnectionAttemptHandler function. This function takes a callback function as an argument, which will be executed before each connection attempt.
Here's a brief summary of the Connection Attempt Handler's functionality:
By using the Connection Attempt Handler, you can customize the connection process and make adjustments as needed. This can be especially useful in scenarios where you need to connect to different brokers or environments.
CleanSession
The CleanSession flag is a crucial setting when connecting to an MQTT broker. It determines whether the broker should deliver any messages saved for the client.
By setting CleanSession to true, you're indicating that no messages saved by the broker should be delivered. This means that any messages that were going to be sent by the client before disconnecting previously but didn't will not be sent upon connecting to the broker.
If CleanSession is false, stored (un)subscribe messages will be discarded, unless SetResumeSubs is enabled. This can be done by calling SetResumeSubs on the ClientOptions instance.
Take a look at this: Docker Client Golang
MQTT Store and Cache
You can set the implementation of the Store interface used for message persistence by calling the SetStore function on a ClientOptions object. This is necessary for QoS levels QoS_ONE or QoS_TWO.
If you don't provide a store, the client will use MemoryStore by default. This is a good option for development or testing, but may not be suitable for production environments.
The MemoryStore has a Del function that deletes a message pointer associated with a given key. This function searches the OrderedMemoryStore and removes the message if the key is found.
This approach can be useful for managing message persistence in your MQTT application.
MQTT Logging and Reporting
Logging is a crucial step in troubleshooting issues with the golang mqtt library. Enabling logging within the library and on your broker can help you identify the root cause of the problem.
The library can produce various levels of log by assigning logging endpoints such as ERROR, CRITICAL, WARN, and DEBUG.

If you're experiencing issues, try to provide a Minimal, Reproducible Example (MRE) to demonstrate the problem. This can be done using Docker, which makes it relatively simple to provide a working end-to-end example.
Here are the essential details to include in your bug report:
- Version of the package you're using (tag or commit)
- Full, clear description of the problem
- Configuration information (code showing how you connect, including all references to ClientOption)
- Broker details (name and version)
Don't forget to include any attempts you've made to resolve the issue, as well as broker logs and application logs covering the period the issue occurred.
Logging
Logging is a crucial step in troubleshooting issues with your MQTT library and broker. Enabling logging is a good way to start.
You can produce various levels of log by assigning the logging endpoints, including ERROR, CRITICAL, WARN, and DEBUG. This can help you identify the root cause of the problem.
For example, you can assign the logging endpoints to see the different levels of log output. This can be a useful tool in your troubleshooting efforts.
Logging can be enabled within the library and on your broker, giving you a more comprehensive view of what's happening. This can be especially helpful when dealing with complex issues.
Reporting Bugs
Reporting bugs is an essential part of the development process, and it's great that this library welcomes bug reports. A significant percentage of issues reported are not resolved due to a lack of information.
To ensure that your bug report is actionable, it's crucial to include specific details such as the version of the package you're using, which can be found in your go.mod file. This information will help the developers narrow down the issue.
A full, clear, description of the problem is also necessary, detailing what you're expecting versus what actually happens. This will help the developers understand the issue and reproduce it.
Including configuration information, such as code showing how you connect, is also important. This will help the developers understand how the issue is occurring. Please include all references to ClientOption.
Broker details, including the name and version, should also be included. This will help the developers understand the environment in which the issue is occurring.
You might like: Golang Developers
It's also helpful to include details of your attempts to resolve the issue, such as what you've tried, what worked, and what didn't. This will show that you've taken steps to troubleshoot the issue.
A Minimal, Reproducible Example is the best way to demonstrate the issue you're facing. This should include all relevant information, including broker configuration. Docker makes it relatively simple to provide a working end-to-end example.
Broker logs covering the period the issue occurred should also be included. This will help the developers understand the issue from the broker's perspective. Application Logs covering the period the issue occurred are also helpful, unless you've isolated the root cause of the issue.
Here's a list of the information you should include in your bug report:
- Version of the package you're using (tag or commit)
- Full, clear, description of the problem
- Configuration information (code showing how you connect)
- Broker details (name and version)
- Details of your attempts to resolve the issue
- Minimal, Reproducible Example
- Broker logs covering the period the issue occurred
- Application Logs covering the period the issue occurred
Remember, this library doesn't stand alone, it communicates with a broker, so issues you're seeing may be due to bugs in your code, bugs in this library, broker configuration, bugs in the broker, or issues with whatever you're communicating with.
Eclipse Paho
The Eclipse Paho library is a popular choice for building Go applications that need to connect to an MQTT broker. It's a fully open-source project that's widely used in the industry.
Eclipse Paho supports both MQTT 3.1 and 3.11 protocols, giving you flexibility in your project's requirements. This library is specifically designed for Go, making it a great choice for Go developers.
A client supporting MQTT V5 is also available, which is a newer version of the protocol with added features and improvements. This shows that the Eclipse Paho library is actively maintained and updated to support the latest standards.
Take a look at this: Golang Go
MQTT API and Usage
To access the detailed API documentation for the MQTT library, you can use the godoc tool or browse it online through pkg.go.dev.
The library includes samples in the cmd directory for reference, which can be helpful for getting started.
You can use MQTT over websockets by adding the ws:// (unsecure) or wss:// (secure) prefix to the URI.
Use of
To use the MQTT API, you'll need to connect to a public MQTT broker. The free public MQTT broker provided by EMQX is a great option, and it's based on their MQTT IoT cloud platform.
The access information for the server is straightforward. You can find it below.
- Broker: broker.emqx.io
- TCP Port: 1883
- Websocket Port: 8083
These details will help you establish a connection to the MQTT broker and start using the API.
Usage and API
Detailed API documentation is available by using the godoc tool, or can be browsed online using the pkg.go.dev service. This is a great resource for learning how to use the MQTT API.
Samples are available in the cmd directory for reference. These samples can help you get started with using the MQTT API in your own projects.
The library supports using MQTT over websockets by using the ws:// (unsecure) or wss:// (secure) prefix in the URI. This allows you to establish a secure connection to an MQTT server.
If you're running behind a corporate http/https proxy, the library will take into account the environment variables HTTP_PROXY, HTTPS_PROXY, and NO_PROXY when establishing the connection. This can be a big help if you're trying to connect to an MQTT server through a proxy.
Curious to learn more? Check out: Golang Rest Api
MQTT Troubleshooting
Troubleshooting MQTT issues in a GoLang application can be a challenge, but there are some common pitfalls to watch out for. Reviewing the MQTT specification is a good first step, especially if you're new to MQTT.
If you're encountering issues, enabling logging is a good way to begin troubleshooting. This library can produce various levels of log by assigning the logging endpoints, ERROR, CRITICAL, WARN, and DEBUG.
Seemingly random disconnections may be caused by another client connecting to the broker with the same client identifier, which is as per the spec. This can happen if you're not careful with your client identifier.
Unless ordered delivery of messages is essential, set ClientOptions.SetOrderMatters(false) to avoid deadlocks due to blocking message handlers. This will also help you avoid issues with message handlers blocking.
A MessageHandler must not block, unless ClientOptions.SetOrderMatters(false) is set. If you need to perform a long-running task, use a go routine to avoid blocking the handler.

When QOS1+ subscriptions have been created previously and you connect with CleanSession set to false, the broker may deliver retained messages before Subscribe can be called. To process these messages, configure a handler with AddRoute or set a DefaultPublishHandler.
Loss of network connectivity may not be detected immediately. If this is an issue, consider setting ClientOptions.KeepAlive to send regular messages to check the link is active.
Reusing a Client is not completely safe. After calling Disconnect, create a new Client (NewClient()) rather than attempting to reuse the existing one.
Featured Images: pexels.com

