SoFunction
Updated on 2025-03-05

Sample code for communicating with MQTT using Go language

Preparation

Before you begin, make sure you have completed the following preparations:

  • Install the development environment for the Go programming language
  • Understand the basic concepts and working principles of the MQTT protocol
  • Select an MQTT server or proxy as the message transit site, such as Eclipse Mosquitto

Install MQTT Go library

The Go community provides many excellent MQTT client libraries, among which /eclipse/ is the most commonly used. You can install the library using Go's package management tool:

go get /eclipse/

Create an MQTT client

Next, we will use Go to create an MQTT client and connect to the MQTT server. Below is a sample code

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	MQTT "/eclipse/"
)

func main() {
	// Create MQTT client configuration	opts := ()
	("tcp://localhost:1883")
	("go-mqtt-client")

	// Create an MQTT client instance	client := (opts)

	// Connect to the MQTT server	if token := (); () && () != nil {
		(())
	}

	// Subscribe and publish after successful connection	go func() {
		// Subscribe to the topic		if token := ("my/topic", 0, nil); () && () != nil {
			(())
		}

		// Post a message		for i := 0; i < 5; i++ {
			text := ("Message %d", i)
			token := ("my/topic", 0, false, text)
			()
			("Published:", text)
			()
		}
	}()

	// Wait for exit signal	c := make(chan , 1)
	(c, )
	<-c

	// Disconnect from the MQTT server	(250)
}


In the above example code, we create an MQTT client instance and connect to the MQTT server using the Connect() method. We then subscribe and publish after the connection is successful. You can customize topics, message content and QoS levels based on actual needs

This is the article about example codes for communicating with MQTT using Go language. For more information about communication between Go and MQTT, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!