connectmq

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 11 Imported by: 0

README

mqtt-go: Go client for the ConnectMQ public MQTT broker

Go Reference

Publish and subscribe on the free public MQTT broker broker.connectmq.com from Go, with no account needed. This package wraps Eclipse Paho and adds context-aware helpers. It supports TCP, TLS, WebSocket and secure WebSocket. It also works with private brokers created on connectmq.com.

go get github.com/connectmq/mqtt-go

Requires Go 1.24 or later.

Quick start

package main

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

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

func main() {
	ctx := context.Background()
	c, err := connectmq.Connect(ctx, nil) // mqtts://broker.connectmq.com:8883
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	prefix := connectmq.TopicPrefix() // e.g. "connectmq/demo/7f3a91"

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

	// []byte and string are sent as-is; other values are encoded as JSON.
	err = c.Publish(ctx, prefix+"/temperature", map[string]float64{"value": 21.5}, 1, false)
	if err != nil {
		log.Fatal(err)
	}
	time.Sleep(time.Second)
}

The public area is shared, so use a random prefix to keep your topics apart from other testers.

API

Function / method Description
Connect(ctx, *Options) Connects; nil options mean the public broker over TLS
(*Client).Publish(ctx, topic, payload, qos, retain) Publishes and waits for the acknowledgement (QoS 1/2)
(*Client).Subscribe(ctx, filter, qos, handler) Calls handler for every message; returns an unsubscribe function
(*Client).Messages(ctx, filter, qos) Channel of messages, closed when ctx ends
(*Client).WaitForMessage(ctx, filter) Next message (retained messages count)
(*Client).Close(), URL(), IsConnected(), Paho() Connection management; Paho() gives the underlying client
Publish(ctx, topic, payload, qos, retain, *Options) One message with a short-lived connection
Test(ctx, *Options) Connects, publishes, receives; returns TestResult{OK, URL, Connect, RoundTrip, Err}
TopicPrefix(), TopicMatches(filter, topic), BrokerURL(transport, host) Helpers

A Message has the fields Topic, Payload, QoS, Retained and Received, plus the methods String() and JSON(v).

Options
Field Default
Transport connectmq.TLS (TCP 1883, TLS 8883, WS 8083, WSS 8084)
Host broker.connectmq.com
Port Standard port of the transport
ClientID go- plus a random suffix
Username, Password Empty (not needed on the public broker)
KeepAlive, Timeout 60 s, 10 s
Configure func(*paho.ClientOptions) for a last will, certificates or other Paho options

The client uses MQTT 3.1.1 and reconnects automatically.

Examples

Range over messages

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

messages, err := c.Messages(ctx, "connectmq/demo/7f3a91/sensors/+", 0)
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)
	}
}

Private ConnectMQ broker

c, err := connectmq.Connect(ctx, &connectmq.Options{
	Host:      "YOUR_BROKER_HOST",
	Transport: connectmq.TLS,
	Username:  os.Getenv("MQTT_USERNAME"),
	Password:  os.Getenv("MQTT_PASSWORD"),
})

CLI

go install github.com/connectmq/mqtt-go/cmd/connectmq@latest

connectmq test                                       # connectivity and round-trip
connectmq info                                       # endpoints and limits
connectmq prefix                                     # random topic prefix
connectmq sub "connectmq/demo/7f3a91/#"
connectmq pub -q 1 -r connectmq/demo/7f3a91/temp '{"value":21.5}'
echo hello | connectmq pub connectmq/demo/7f3a91/msg

Flags go before the topic: -t tcp|tls|ws|wss, -host, -port, -q 0|1|2, -r (retain), -n <count> and -json (sub), -u and -p (credentials).

Public broker

Protocol URL
MQTT (TCP) mqtt://broker.connectmq.com:1883
MQTT over TLS mqtts://broker.connectmq.com:8883
WebSocket ws://broker.connectmq.com:8083/mqtt
Secure WebSocket wss://broker.connectmq.com:8084/mqtt

Access is anonymous, but the client ID must not be empty. Limits: 64 KB per message, 10 messages per second and 10 subscriptions per client, topics up to 8 levels deep, and sessions expire after at most 30 minutes.

Everything on the public broker is public. Any client can subscribe to #. Use the broker only for testing, and always under a random topic prefix. For production, create a private broker with its own credentials at connectmq.com.

More: Free Public MQTT Broker for Testing. Also available for Python (pip install connectmq), Node.js (@connectmq/mqtt), .NET (ConnectMQ.Mqtt), Node-RED (node-red-contrib-connectmq) and PowerShell (MQTTBroker).

Testing

go test ./...          # includes live tests against broker.connectmq.com
go test -short ./...   # offline tests only

License

MIT

Documentation

Overview

Package connectmq is an MQTT client preconfigured for the free public broker broker.connectmq.com, built on Eclipse Paho (github.com/eclipse/paho.mqtt.golang).

It connects anonymously over TCP (1883), TLS (8883), WebSocket (8083) or secure WebSocket (8084), and adds context-aware Publish, Subscribe, Messages and WaitForMessage helpers on top of Paho.

Everything on the public broker can be read by anyone: use it for testing only, and put your topics under a random prefix (see TopicPrefix). For production, create a private broker at https://connectmq.com and set Options.Host, Options.Username and Options.Password.

Example

Publish and subscribe on the public broker with one connection.

package main

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

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

func main() {
	ctx := context.Background()
	c, err := connectmq.Connect(ctx, nil) // mqtts://broker.connectmq.com:8883
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	prefix := connectmq.TopicPrefix() // e.g. "connectmq/demo/7f3a91"
	unsubscribe, err := c.Subscribe(ctx, prefix+"/#", 0, func(m connectmq.Message) {
		fmt.Println(m.Topic, m.String())
	})
	if err != nil {
		log.Fatal(err)
	}
	defer unsubscribe()

	// Values other than []byte and string are sent as JSON.
	if err := c.Publish(ctx, prefix+"/temperature", map[string]float64{"value": 21.5}, 1, false); err != nil {
		log.Fatal(err)
	}
	time.Sleep(time.Second)
}

Index

Examples

Constants

View Source
const BrokerHost = "broker.connectmq.com"

BrokerHost is the host name of the ConnectMQ public broker.

Variables

This section is empty.

Functions

func BrokerURL

func BrokerURL(t Transport, host string) string

BrokerURL returns the URL of a broker endpoint, for example "mqtts://broker.connectmq.com:8883". An empty host means BrokerHost.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(connectmq.BrokerURL(connectmq.WSS, ""))
}
Output:
wss://broker.connectmq.com:8084/mqtt

func Publish

func Publish(ctx context.Context, topic string, payload any, qos byte, retain bool, opts *Options) error

Publish sends one message using a short-lived connection (nil opts means the public broker over TLS).

func TopicMatches

func TopicMatches(filter, topic string) bool

TopicMatches reports whether topic matches an MQTT topic filter with the wildcards + and #, including shared subscriptions ($share/group/filter).

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(connectmq.TopicMatches("plant/+/temp", "plant/line1/temp"))
	fmt.Println(connectmq.TopicMatches("plant/#", "plant/line1/temp"))
	fmt.Println(connectmq.TopicMatches("plant/+", "plant/line1/temp"))
}
Output:
true
true
false

func TopicPrefix

func TopicPrefix() string

TopicPrefix returns a random topic prefix such as "connectmq/demo/7f3a91". The public area is shared, so a random prefix keeps your topics apart from other testers.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a connected MQTT client. Close it when done.

func Connect

func Connect(ctx context.Context, opts *Options) (*Client, error)

Connect opens a connection to the broker described by opts (nil means the public broker over TLS).

Example (PrivateBroker)

Connect to a private ConnectMQ broker.

package main

import (
	"context"
	"log"

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

func main() {
	c, err := connectmq.Connect(context.Background(), &connectmq.Options{
		Host:      "YOUR_BROKER_HOST",
		Transport: connectmq.TLS,
		Username:  "device01",
		Password:  "secret",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
}

func (*Client) Close

func (c *Client) Close()

Close disconnects from the broker.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected reports whether the connection is currently up.

func (*Client) Messages

func (c *Client) Messages(ctx context.Context, filter string, qos byte) (<-chan Message, error)

Messages subscribes to filter and delivers messages on the returned channel until ctx is cancelled; the channel is then closed and the subscription removed. Messages are dropped if the channel buffer (64) is full.

Example
package main

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

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, err := connectmq.Connect(ctx, &connectmq.Options{Transport: connectmq.WSS})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	messages, err := c.Messages(ctx, "connectmq/demo/7f3a91/sensors/+", 0)
	if err != nil {
		log.Fatal(err)
	}
	for m := range messages { // ends when ctx is done
		var reading struct{ Temperature float64 }
		if err := m.JSON(&reading); err == nil {
			fmt.Println(m.Topic, reading.Temperature)
		}
	}
}

func (*Client) Paho

func (c *Client) Paho() paho.Client

Paho returns the underlying Paho client, for anything not covered by this package.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, topic string, payload any, qos byte, retain bool) error

Publish sends a message. A []byte or string payload is sent as is; any other value is encoded as JSON. Publish an empty payload with retain=true to clear a retained message. For QoS 1 and 2 it waits for the broker's acknowledgement.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, filter string, qos byte, handler func(Message)) (unsubscribe func() error, err error)

Subscribe calls handler for every message matching filter, on a Paho goroutine. The returned function unsubscribes. Only one handler per filter is active at a time.

func (*Client) URL

func (c *Client) URL() string

URL returns the broker URL this client is connected to.

func (*Client) WaitForMessage

func (c *Client) WaitForMessage(ctx context.Context, filter string) (Message, error)

WaitForMessage returns the next message matching filter, or an error when ctx ends. Retained messages count, so it returns immediately if one is stored for the topic.

Example
package main

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

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	c, err := connectmq.Connect(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	m, err := c.WaitForMessage(ctx, "connectmq/demo/7f3a91/reply")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(m.String())
}

type Message

type Message struct {
	Topic    string
	Payload  []byte
	QoS      byte
	Retained bool
	Received time.Time
}

Message is a received MQTT message.

func (Message) JSON

func (m Message) JSON(v any) error

JSON decodes the payload into v.

func (Message) String

func (m Message) String() string

String returns the payload as text.

type Options

type Options struct {
	Transport Transport     // default TLS
	Host      string        // default broker.connectmq.com
	Port      int           // default: the standard port of Transport
	ClientID  string        // default "go-" plus a random suffix; must be unique
	Username  string        // for private brokers
	Password  string        // for private brokers
	KeepAlive time.Duration // default 60s
	Timeout   time.Duration // connect and acknowledgement timeout, default 10s

	// Configure, when set, is called with the Paho options before connecting,
	// for settings such as a last will or custom TLS certificates.
	Configure func(*paho.ClientOptions)
}

Options configures Connect. The zero value connects anonymously to the public broker over TLS with a random client ID.

type TestResult

type TestResult struct {
	URL       string
	OK        bool
	Connect   time.Duration
	RoundTrip time.Duration
	Err       error
}

TestResult is the result of Test.

func Test

func Test(ctx context.Context, opts *Options) TestResult

Test connects, subscribes, publishes and receives a test message. Errors are reported in TestResult.Err.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	r := connectmq.Test(context.Background(), &connectmq.Options{Transport: connectmq.TLS})
	if r.OK {
		fmt.Printf("connected in %v, round-trip %v\n", r.Connect, r.RoundTrip)
	} else {
		fmt.Println("failed:", r.Err)
	}
}

type Transport

type Transport string

Transport selects how the client reaches the broker.

const (
	TCP Transport = "tcp" // MQTT over TCP, port 1883
	TLS Transport = "tls" // MQTT over TLS, port 8883
	WS  Transport = "ws"  // MQTT over WebSocket, port 8083, path /mqtt
	WSS Transport = "wss" // MQTT over secure WebSocket, port 8084, path /mqtt
)

Supported transports.

Directories

Path Synopsis
cmd
connectmq command
Command connectmq is an MQTT command-line client for the free public broker broker.connectmq.com.
Command connectmq is an MQTT command-line client for the free public broker broker.connectmq.com.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL