Skip to content

Go ​

The official github.com/connectmq/mqtt-go package wraps Eclipse Paho with context-aware helpers for ConnectMQ: TLS by default, values encoded as JSON, and subscriptions as handlers or channels.

How it connects ​

Go service connecting to ConnectMQ A Go service uses github.com/connectmq/mqtt-go · built on Eclipse Paho to connect to broker.connectmq.com over MQTT · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authGo servicegithub.com/connectmq/mqtt-go · built on Eclipse Pahoc.Publish(ctx, "acme/istanbul/assembly/line1/cnc-01/telemetry", reading, 1, false)Values encoded as JSON · subscriptions as handlers or channelsMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

bash
go get github.com/connectmq/mqtt-go

Requires Go 1.24 or later.

Publish and subscribe ​

go
package main

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

	connectmq "github.com/connectmq/mqtt-go"
)

func main() {
	ctx := context.Background()

	c, err := connectmq.Connect(ctx, &connectmq.Options{
		Transport: connectmq.TLS,                              // mqtts://broker.connectmq.com:8883
		ClientID:  os.Getenv("CMQ_CLIENT_ID") + "_go-service", // issued client ID + "_" + suffix
		Username:  os.Getenv("CMQ_USERNAME"),
		Password:  os.Getenv("CMQ_PASSWORD"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	unsubscribe, err := c.Subscribe(ctx, "acme/istanbul/#", 1, func(m connectmq.Message) {
		fmt.Println(m.Topic, m.String())
	})
	if err != nil {
		log.Fatal(err)
	}
	defer unsubscribe()

	for {
		// []byte and string are sent as they are; other values are encoded as JSON
		reading := map[string]float64{"temperature": 62.4, "spindleRpm": 11950}
		if err := c.Publish(ctx, "acme/istanbul/assembly/line1/cnc-01/telemetry", reading, 1, false); err != nil {
			log.Println("publish:", err)
		}
		time.Sleep(5 * time.Second)
	}
}
bash
CMQ_CLIENT_ID=connectmq_client_123456 CMQ_USERNAME=cmq_xxxx CMQ_PASSWORD='...' go run .

With QoS 1 or 2, Publish returns when the broker acknowledges the message. c.Paho() returns the underlying Paho client.

Always set ClientID

Without ClientID the package uses a random go-... ID, which your private broker refuses with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per process (why).

Range over messages ​

Messages returns a channel that closes when the context ends:

go
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

messages, err := c.Messages(ctx, "acme/istanbul/+/+/+/telemetry", 1)
if err != nil {
	log.Fatal(err)
}
for m := range messages {
	var reading struct{ Temperature float64 }
	if m.JSON(&reading) == nil {
		fmt.Println(m.Topic, reading.Temperature)
	}
}

c.WaitForMessage(ctx, filter) returns the next message (a retained message counts). A Message has Topic, Payload, QoS, Retained and Received, plus String() and JSON(v).

Options ​

FieldDefaultNotes
Transportconnectmq.TLSTLS 8883, WSS 8084, TCP 1883, WS 8083
Hostbroker.connectmq.com
ClientIDgo- + randomSet it to <issued client ID>_<suffix>
Username, PasswordemptyFrom MQTT Connection Settings
KeepAlive, Timeout60 s, 10 s
Configurenonefunc(*paho.ClientOptions) for a last will and other Paho options

Reconnecting ​

The client uses MQTT 3.1.1 and reconnects automatically, so Publish works again once the network is back. It starts each connection with a clean session, so subscriptions are not restored after a reconnect. For a long-running subscriber, check c.IsConnected() periodically and subscribe again after a reconnect, or close the client and call Connect again.

Test from the command line ​

bash
go install github.com/connectmq/mqtt-go/cmd/connectmq@latest
connectmq test        # connect, publish, receive against the public test broker

The public test broker needs no account, but anyone can read its topics: use it for experiments only, under a random prefix such as connectmq/demo/7f3a91/.

Fully managed MQTT broker for connected devices.